React State
What is React state?
const App = () => {
const [brickColor, setBrickColor] = useState("red");
return (
<div className="brick"
style={{ background: brickColor }}
/>
)
}useState basics
const App = () => {
const [brickColor, setBrickColor] = useState("red");
return (
<div className="brick"
style={{ background: brickColor }}
onClick={() => setBrickColor("blue")}
/>
)
}useState - update state
useState - representing multiple values
// Multiple useState
const App = () => {
const [brickColorOne, setBrickColorOne] = useState("red");
const [brickColorTwo, setBrickColorTwo] = useState("red");
// ... 22 other useState
return (
<>
<div className="brick"
style={{ background: brickColorOne }}
onClick={() => setBrickColorOne("blue")}
/>
<div className="brick"
style={{ background: brickColorTwo }}
onClick={() => setBrickColorTwo("blue")}
/>
// ... 22 other divs
</>
)
}
useState - representing multiple components
// One useState for each set of colours
const App = () => {
// All player brick colours are stored in one array
// Currently 2 elements, meaning 2 bricks.
// Can easily scale this array to the number of bricks we want the player to have
// e.g. 12, 24, 100, etc.
const [playerBrickColors, setPlayerBrickColors] =
useState(["red", "red", /* 10 other values */]);
// All computer brick colours are stored in one array
const [computerBrickColors, setComputerBrickColors] =
useState(["red", "red", /* 10 other values */ ]);
return (
<>
<div className="brick"
style={{ background: playerBrickColors[0] }}
onClick={() => {
const newBrickColors = [...playerBrickColors];
newBrickColors[0] = "blue";
setPlayerBrickColors(newBrickColors)
}}
/>
// ... the rest of the divs below
</>
)
}useState - representing multiple components
// One useState for each set of colours
const App = () => {
const [playerBrickColors, setPlayerBrickColors] = useState(["red", "red"]);
const [computerBrickColors, setComputerBrickColors] = useState(["red", "red"]);
return (
<>
{playerBrickColors.map((playerBrickColor, index) => {
return (
<div className="brick"
style={{ background: /* 🌟 What should be here? */ }}
onClick={() => {
/* 🌟 What should be here? */
}}
/>
)
}}}
// ... computer bricks below
</>
)
}useState - representing multiple components