Controlled Input Field
Create an input field component that allows a user to type in text and displays the text in real-time.
Every time the user types something in the input field, the text should update in the text element
You should use the useState hook to keep track of the text state
Solution Walkthrough for Controlled Input Field
Spoiler Alert!
Don't read this unless you've already solved the problem.
Controlled Components:
In React, a controlled component is a component where the state of the input field is directly controlled by React. The value of the input field is set by a state variable, and any change in the value triggers an event handler to update the state.
text
with an empty string:text
using the useState
hook and set its initial value to an empty string.const [text, setText] = useState('');
handleInputChange
function:handleInputChange
that takes the event
object as a parameter. This function is responsible for updating the text
state variable with the current value of the input field.function handleInputChange(event) {
setText(event.target.value);
}
Set up the controlled input field component:
value
attribute of the input field to the current text state. This makes the input field a controlled component, as its value is directly controlled by React.handleInputChange
function to the input field's onChange
event handler:handleInputChange
function to the onChange
event handler of the input field. This ensures that the function is called every time the input field's value changes.<input type="text" value={text} onChange={handleInputChange} />
Display the text in real-time:
text
state variable to display the current text in a paragraph element.<p>Input text: {text}</p>