0
0
Reactframework~30 mins

Multiple state variables in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Managing Multiple State Variables in React
📖 Scenario: You are building a simple user profile form in React. The form will collect a user's first name and last name. You want to store these two pieces of information separately in the component's state.
🎯 Goal: Create a React functional component that uses two separate state variables to hold the firstName and lastName. Then display the full name by combining these two states.
📋 What You'll Learn
Use React functional component syntax
Use useState hook twice to create two state variables: firstName and lastName
Initialize firstName with the string "John"
Initialize lastName with the string "Doe"
Render a <div> that shows the full name by combining firstName and lastName with a space in between
💡 Why This Matters
🌍 Real World
Managing multiple pieces of user input separately is common in forms, profile pages, and settings in web apps.
💼 Career
Understanding how to handle multiple state variables and controlled inputs is essential for React developers building interactive user interfaces.
Progress0 / 4 steps
1
Set up the React component and initial state variables
Create a React functional component called UserProfile. Inside it, use the useState hook to create a state variable called firstName and initialize it with the string "John". Also create a state variable called lastName and initialize it with the string "Doe". Import useState from react.
React
Need a hint?

Remember to import useState from react. Use const [state, setState] = useState(initialValue) syntax.

2
Add JSX to display the full name
Inside the UserProfile component, return a <div> element that displays the full name by combining the firstName and lastName state variables separated by a space.
React
Need a hint?

Use JSX syntax to return a <div> with curly braces to insert the state variables.

3
Add input fields to update the first and last names
Add two <input> fields inside the returned JSX. The first input should have its value set to firstName and update firstName using setFirstName on change. The second input should have its value set to lastName and update lastName using setLastName on change.
React
Need a hint?

Use controlled inputs by setting value and onChange handlers that update the state.

4
Add accessibility labels and wrap inputs in a form
Wrap the two input fields inside a <form> element. Add aria-label attributes to the inputs: aria-label="First Name" for the first input and aria-label="Last Name" for the second input to improve accessibility.
React
Need a hint?

Use a <form> tag to group inputs and add aria-label attributes for screen readers.