0

I understand the concept of the Controlled component however when I think about it deeply why do we actually need it if we are using onChange method.because everytime we make some change the value of that change will be in the state so there will be a one source of truth either way. why do we need value for making it a controlled component?

<input
    name="username"
    onChange={this.onChange}
    value={this.state.username}
    type='text'
    placeholder="Full Name"
 />
Michale Rezene
  • 350
  • 2
  • 12

3 Answers3

0

Because if you don't set the value on the <input> element:

value={this.state.username}

Then when the state is updated and the component re-renders it won't display a value in the UI. Regardless of the state tracked by React, ultimately the UI needs to render as plain HTML. And you need to tell that HTML what the value for that <input> is so it displays (and can be further modified).

David
  • 208,112
  • 36
  • 198
  • 279
0

well, let's think about it.

if it is a controlled component, it means that you can do whatever you want from the input on the onChange function right? well, now think that you are for some reason transforming the input from the user, lets think about a function that changes numbers:

onChange(event){
    const inputValue = event.target.value;
    const result = '$' + inputValue + '.00';
    this.setState({ value});
}

right? well, basically, this tell us how we changed our state value but how does the input know about these change and the real value we want to show? how does the input know that if the user puts something it should show something else?

12 ---> $12.00

when you control an field, you need to handle the output and the input of these field, because you need to provide everything in order to properly show the data.

if you are not doing any weird magic, maybe you don't need a controlled input.

Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0

The pattern of separating out 'what happened' from 'what this does to my app' flows directly from React's use of a declarative style of programming (in comparison to imperative - see this post if you're not familiar with the distinction).

It takes a bit of getting used to when you first encounter it but as your code increases in complexity it makes more and more sense as it keeps things de-coupled and makes it easy to reason about. Changes start as events, which update the state, which is then reflected in your app. It's a loop rather than a 2-way binding.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46