Use onSubmit Event in React Functional Components

Create new folder named LearnReactJSWithRealApps and select to this folder in Visual Studio Code

Open Terminal windows in Visual Studio Code and use commands below:

npm install create-react-app@latest
npx create-react-app myapp




Open App.js file in src folder and create new component as below:

import React, { useState } from 'react';

function App() {

  let [account, setAccount] = useState({
    username: '',
    password: '',
    description: ''
  });

  let search = (e) => {
    e.preventDefault();
    let keyword = e.target.elements.keyword.value;
    console.log('Keyword: ' + keyword);
  }

  let handleChange = (e) => {
    let name = e.target.name;
    let value = e.target.value;
    account[name] = value;
    setAccount(account);
  }

  let save = (e) => {
    e.preventDefault();
    console.log(account);
  }

  return (
    <div>

      <fieldset>
        <legend>Demo 1</legend>
        <form method="post" onSubmit={search}>
          <input type="text" name="keyword" placeholder="Input keyword..." />
          <input type="submit" value="Search" />
        </form>
      </fieldset>

      <fieldset>
        <legend>Demo 2</legend>
        <form method="post" onSubmit={save}>
          Username <input type="text" name="username" onChange={handleChange} />
          <br />
          Password <input type="password" name="password" onChange={handleChange} />
          <br />
          Description
          <br />
          <textarea name="description" cols="20" rows="5" onChange={handleChange}></textarea>
          <br />
          <input type="submit" value="Save" />
        </form>
      </fieldset>

    </div>
  );
};

export default App;




Open index.js file in src folder and add new component to this file as below:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

In Terminal windows in Visual Studio Code and type: npm start,
program will open url http://localhost:3000 on browser




Click buttons to call onSubmit events