
React: How To Get Input Value (Dynamic Text Input)
How to set, change and get value of input HTML element in React, when typed in.
This Input Box React tutorial is based on following YouTube video:
In React you can't use global or loose component variables (defined with var, let or const keywords directly inside component's contructor, without useState hook) if your goal is to wire them into dynamically updated elements in the app's view.
This includes HTML's text input element (textarea is another example.)
Instead, you will want to first create a state variable using useState hook. This is the value that will change in text input. Any time you want to get it in React, simply output its value.
However, in order to actually update, modify or change it physically in the input field, you will need to override input field's onChange event, grab the value from the event, and update state variable with it.
The setup is to create onChange event handler to get event.target.value text input value, and only then set it to state value (using setVal setter function, see below...)
Your function will execute whenever text in the input field changes.
Here's source code for getting the value of a changing input component:
import { useState } from 'react' function App() { const [val, setVal] = useState("Hello there") // Get input value on click const click = color => { alert(val) } /* This is where we actually change (set) value of the input box */ const change = event => { setVal(event.target.value) } /* Display clickable button */ return (<div className = "App"> <input onChange = {change} value = {val} /> <button onClick = {click}>Get Input Value</button> </div>) } export default App;
This is the basic workflow for adding state values to components in React.
Before changing, setting and getting text field value, just wire it as shown in this example.
Getting input value in react means simply getting the state value created earlier with useState hook.
Image from this tutorial:

