React: How to get a value of an input element (feat. React Hooks)

The form is the most common way to get data from a user. You can get the value of the input easily by using useRef() of React Hooks.

Form.jsx

import React, { useRef } from 'react';

const Form = () => {
    const nameRef = useRef();

    const onSubmit = (event) => {
        event.preventDefault();
        const name = nameRef.current.value;
        console.log(name);
    };

    return (
        <form>
            <input ref={nameRef} name='name' placeholder='Name' />
            <button onClick={onSubmit}>Submit</button>
        </form>
    );
};

export default Form;
  1. create an object: const nameRef = useRef()
  2. pass the obejct by using ref attribute in input element
  3. assign the value: const name = nameRef.current.value

App.jsx

import { Component } from 'react';
import './app.css';
import Form from './components/form';

class App extends Component {

    render() {
        return (
            <Form />
        );
    }
}

export default App;

Result

Screen Shot 2020-12-13 at 13.58.47.png

Reference: React Hooks