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;
- create an object:
const nameRef = useRef()
- pass the obejct by using
ref
attribute ininput
element - 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
Reference: React Hooks