Skip to main content

Part 3: About States

For React to capture changes and interactions in the application, it uses a concept called state. A state is a JavaScript object that stores a component's dynamic data and determines the component's behavior. When the state of a component changes, the component re-renders.

  1. In the WelcomeView.jsx file, we need to add a state to store the user's name. We can do this by using the useState hook provided by React. The useState hook returns a stateful value and a function to update it. The initial value of the state is passed as an argument to the useState hook.
src/components/WelcomeView.jsx
import { useState } from "react";

const WelcomeView = () => {
const [userName, setUserName] = useState("");

return (
<div id="welcome-screen">
<form id="name-form">
<div className="form-group">
<label htmlFor="username">Type your name: </label>
<input
value={userName}
onChange={(e) => {setUserName(e.target.value)}}
className="form-control"
type="text"
id="username"
name="username"
required placeholder="Enter Name Here..." minLength="2"
maxLength="15" />
</div>
<button class="btn btn-primary" id="start-game-button" type="button">
Start Game!
</button>
</form>
</div>
);
};