I'm new to React. I have a rating component that I created. The problem I'm having is onClick I can see the rating is updating in the console, but on the page I don't see the change happening. My understanding is that React components need to be pure functions and it's better to prefer functional components over classes. When I try to use the useState hook my rating is added to the previous state and doesn't update correctly on the page.
My first question is what is the best/preferred way to update state within a component? If I'm using a functional component do I have to use a hook?
Please see my code below
export default function Rating(props) {
let stars = [];
// const [stars, setStars] = useState([]);
let star = '☆';
for (let i = 0; i < props.stars; i++) {
stars.push(star);
}
function rate(index) {
let filledStar = '★'
let stars = [];
// setStars([])
for (let i = 0; i < props.stars; i++) {
stars.push(star);
}
stars.forEach((star, i) => {
while (index >= 0) {
stars[index] = filledStar;
index--;
}
})
console.log('stars filled', stars)
return stars
}
return (
<>
<div className="stars">
{stars.map((star, i) => (
<h2
key={i}
onClick={() => rate(i)}>{star}
</h2>
))}
</div>
</>
)
}
If I click the fourth star this is returned as expected, but the UI doesn't update.
