I'm learning react. I built a page that let user vote for different person. I was able to make the voting work. But I'd like to highlight the person who gets the most votes.
This requires to compare states. I'm not quite sure how to do it. The hint that I got is from reading stackoverflow is to store the state in the parent component instead of in the the child. I can't figure out how to do it with my code, especially with useState hook.
import React, { useState } from "react";
const employeeDirectory = [
{
firstName: "Alice",
lastName: "A",
id: 1,
},
{
firstName: "Bob",
lastName: "B",
id: 2,
},
{
firstName: "Cathy",
lastName: "C",
id: 3,
},
];
function App() {
return (
<div className="App">
<header className="App-header">
<h1>Vote for me</h1>
{employeeDirectory.map((i) => {
const { firstName, lastName, id } = i;
return (
<Profile
key={id}
firstName={firstName}
lastName={lastName}
id={id}
/>
);
})}
</header>
</div>
);
}
const Profile = (props) => {
console.log(props);
const { firstName, lastName, id } = props;
const [count, setCount] = useState(0);
return (
<div
style={{
background: id === 1 ? "yellow" : "white",
}}
>
<h2>
Name: {firstName} {lastName}
</h2>
<p>
{firstName} received {count} votes.
</p>
<button onClick={() => setCount(count + 1)}>Vote for me</button>
</div>
);
};
export default App;