Learn to use one of the built-in React hooks, useState
, to make a single controlled input work.
We'll do this by creating a name
state variable, and a handleNameChange
function to update that state variable.
Note: you need to be using a version of React that supports Hooks (versions 16.8.0 and higher)
Instructor: [00:00] We will start by creating a name variable that will hold the current value of the input. We'll go ahead and create the new input, give it a value of name. We're also supposed to give it an onChange prop, which will be a function that gets the new user input, and is supposed to update the name variable somehow.
[00:29] We'll do onChange equals handleNameChange, create a new variable called handleNameChange. It will be a function that accepts an event. We can get the value of whatever user typed using event.target.value.
[00:54] We're then supposed to use newValue to somehow update the name variable, but we cannot do just name equals newValue, but React will not know that something changed. Instead, we will convert name to a state variable using React hook called useState.
[01:17] const name, set name from React useState. We'll give it a default value of Joe. Now, we can call setName(newValue) in the handleNameChange function. If we type something into the input, we can see that its value is updating.
[01:45] We can also just use the name variable somewhere in render outside the input, just to make sure that they are both in sync.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!