FAQ: React Forms - Update an Input's Value

This community-built FAQ covers the “Update an Input’s Value” exercise from the lesson “React Forms”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Learn ReactJS: Part II

FAQs on the exercise Update an Input’s Value

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

what is the purpose of step 1 of this exercises? That is, how does adding the value attribute do anything? I tried running without it, and the h1 was still responsive to my input.

5 Likes

I’m wondering the same…

1 Like

I’m not 100% sure, but it seems that setting the value attribute to be this.state.userInput makes the Input component “controlled” (see the next exercise entitled Controlled vs Uncontrolled). The React documentation on forms says that the <input /> element has its own state (what users enter) by default. The React component also stores it as its own state. We don’t want two truths to exist. So we override the <input/> element’s state with the React component’s state.

Can someone confirm if my answer is correct?

3 Likes

Here’s a StackOverflow explanation: reactjs - is value attribute necessary in a react component's input? - Stack Overflow.

Basically, it doesn’t really matter in this example but setting the value={state} is usually a good idea. It prevents something other than the input changing the state and getting the input and the state out of sync. For example, assume I have a button that sets the userInput to ‘banana.’ If I type ‘apple’ into the input, then click the button, the userInput is now set to ‘banana’ but the input still says ‘apple.’ Using value={userInput} when we click the button, the input text will change as well.

I hope this helps!

1 Like