When working with forms in React, it is often necessary to obtain the value of a specific form field. This can be helpful, for instance, when a user clicks a button and you need to access the input data. In this article, we will explore how to retrieve the value of an input element in React.
To achieve this, we can make use of React hooks. Hooks allow us to manage state in functional components. In our case, we will create a state variable for each input field and listen for the onChange
event to update the state variable with the new value.
Let’s take a look at an example:
import React, { useState } from 'react';
const MyForm = () => {
const [title, setTitle] = useState('');
return (
<form>
<input onChange={event => setTitle(event.target.value)} />
</form>
);
};
export default MyForm;
In the code snippet above, we use the useState
hook to create a state variable title
and its corresponding update function setTitle
. The initial value of title
is set to an empty string.
Inside the JSX code, we attach an onChange
event listener to the input element. When the input value changes, the event handler function is executed. This function receives the event object as the argument, from which we extract the new value using event.target.value
. We then call setTitle
and pass the new value to update the state variable.
Later, when handling the submit event of the form or wherever we need to access the input value, we can simply retrieve it from the title
variable.
By utilizing this approach, we can easily obtain the value of any input element in React.