0
0
Reactframework~30 mins

Controlled components in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Controlled Components in React
📖 Scenario: You are building a simple React form where users can type their name. The form input should be controlled by React state to keep the input value in sync with the component.
🎯 Goal: Create a React functional component with a controlled text input. The input value should be stored in state and updated as the user types.
📋 What You'll Learn
Create a React functional component named NameForm
Initialize a state variable called name with an empty string
Add an <input> element of type text controlled by the name state
Update the name state on every input change using an onChange handler
💡 Why This Matters
🌍 Real World
Controlled components are used in React forms to keep the UI and data in sync, making it easier to validate and manage user input.
💼 Career
Understanding controlled components is essential for React developers building interactive forms and user interfaces.
Progress0 / 4 steps
1
Set up the React component and state
Create a React functional component called NameForm. Inside it, use the useState hook to create a state variable named name initialized to an empty string "".
React
Need a hint?

Use const [name, setName] = useState("") inside the NameForm function.

2
Add the controlled input element
Inside the NameForm component, add an <input> element of type text. Set its value attribute to the name state variable.
React
Need a hint?

Return an <input> element with value={name} inside the component.

3
Add the onChange handler to update state
Add an onChange event handler to the <input> element. The handler should update the name state using setName with the current input value from event.target.value.
React
Need a hint?

Use onChange={event => setName(event.target.value)} on the input element.

4
Complete the component with a label and export
Wrap the <input> in a <label> with the text Name:. Also, add export default NameForm; at the end of the file.
React
Need a hint?

Wrap the input inside <label> with text Name: and add export default NameForm; at the end.