Use Ref 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, { useRef } from 'react';

function App() {

  const refUsername = useRef();
  const refKeyword = useRef();
  const refPassword = useRef();
  const refDescription = useRef();

  let search = (e) => {
    console.log('Keyword: ' + refKeyword.current.value);
  }

  let save = (e) => {
    console.log('Username: ' + refUsername.current.value);
    console.log('Password: ' + refPassword.current.value);
    console.log('Username: ' + refDescription.current.value);
  }

  return (
    <div>

      <fieldset>
        <legend>Demo 1</legend>
        <form method="post">
          <input type="text" ref={refKeyword} placeholder="Input keyword..." />
          <input type="button" value="Search" onClick={search} />
        </form>
      </fieldset>

      <fieldset>
        <legend>Demo 2</legend>
        <form method="post">
          Username <input type="text" ref={refUsername} />
          <br />
          Password <input type="password" ref={refPassword} />
          <br />
          Description
          <br />
          <textarea cols="20" rows="5" ref={refDescription}></textarea>
          <br />
          <input type="button" value="Save" onClick={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

Keyword: pmk
Username: acc1
Password: pw123
Username: Description acc1