Skip to main content

Part 4: Lift State Up

For both the WelcomeView and GameView components to communicate the name with each other, we need to lift the state up to the parent component. This means that the state will be managed by the parent component and passed down to the child components as props.

src/App.jsx
...
import {setState} from 'react';
...

function App() {
const [userName, setUserName] = useState("");

return (
<div class="container">
...
<WelcomeView userName={userName} setUserName={setUserName} />
<GameView userName={userName} />
...
</div>
);
}
src/components/WelcomeView.jsx
import { useState } from "react";

const WelcomeView = ({userName, setUserName}) => {
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>
);
};
src/components/GameView.jsx
const GameView = ({userName}) => {
return (
<div id="game-screen">
<div id="score-tally">
<p id="score"> {UserName}: 0 v CPU: 0</p>
</div>

<form id="game-form">
<div className="form-group">
<label htmlFor="user-selection">Select your choice: </label>
<select
className="custom-select"
id="user-selection"
name="user-selection"
>
<option id="rock" value="rock">
Rock
</option>
<option id="paper" value="paper">
Paper
</option>
<option id="scissors" value="scissors">
Scissors
</option>
</select>
</div>
<button class="btn btn-primary" id="play-button" type="button">
Play
</button>
</form>
</div>
);
};

export default GameView;