logo
logo

Controlled Input Field

Easy

Controlled Input Field

Easy

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

Console
Submit
Solution
00:00

Solution Walkthrough for Controlled Input Field

Key ReactJS Concepts:

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.

Solution Walkthrough:

Initialize state variable
text
with an empty string:
We create a state variable
text
using the
useState
hook and set its initial value to an empty string.
const [text, setText] = useState('');
Create the
handleInputChange
function:
We create a new function called
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:

In the component's JSX, we set the
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.
Attach the
handleInputChange
function to the input field's
onChange
event handler:
We connect the
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:

Finally, we use the
text
state variable to display the current text in a paragraph element.
<p>Input text: {text}</p>