Home > Mobile >  What is 'value' for in an input element in React?
What is 'value' for in an input element in React?

Time:07-05

What is value={} for in React inputs? I currently have a state of const [username, setUsername] = useState(""); and an input element in my form that updates whatever the user is typing in the input to the state.

<input type="text" value={username} name="Username" onChange={({target}) => setPassword(target.value)}/>

Why do i need to specify the value in the input? What is the purpose of having the value be the new state variable? It seems to work fine without the value={} at all if I remove it

CodePudding user response:

Doing it with a value prop is called a "controlled component", and otherwise it's an "uncontrolled component". Both of these approaches are supported in react, but the controlled component gives you more... well... control. If you ever need to do something deviates from the built in behavior of the browser, then you must use a controlled component.

So for example, if you want to take what the user typed and make it upper case, you need a controlled component. If you want to have a button which clears the text of your inputs, you need a controlled component. The only case that works with uncontrolled components is if you want literally what the user types.

https://reactjs.org/docs/uncontrolled-components.html

  • Related