Creating different state value for mapped objects

Hello everyone,
In the code below I built a star component based on the mapped object, but the star rating shows the same value when I click on any of them. how can I make each star rating have its own value based on the selection? pls hellllppppp

  const [value, setValue] = useState(0);

  function handleChange (event, newValue) {
      setValue(newValue)     
  }
  return (
    <>
      <div>
        {data.map((rate, index) => (
          <div   key={rate.index} >

            <p> {rate.label} {project} </p>
            <div>
              <Rating 
              size="large"
              value={rate.value} 
              max={10} 
              
              onChange={handleChange} 
              />

              <p>{value}</p>

            </div>
          </div>
        ))}
      </div>

      
    </>

from the above image, the rating should show 7, 6, 9 rating, respectively

the newValue is showing the correct value (each) in the console, but in the browser everything is updating at the same time

Here is the codesandbox template sir

I think creating different state for each ratings might solve my problem but i couldn’t think of arranging the codes

You need a single source of truth for the state which in this case would be the mapped data. The state you map is the state you update.

You should create a rating component and map that. Lift the state up and pass the component the props it needs along with the state updater function. Presumably, the ratings are going to be part of something, like a product card or whatnot, so it doesn’t make sense to map the MUI rating component on its own anyway.

The updater function can map over the state, find the object it needs to update the rating for and return a new object with the updated rating value. The assumption here is an array of objects, like an array of product objects with a rating property.

1 Like

I created the rating component based on the data i have, thats why i have 3 star ratings.

And if i get your point, you want me to add array of value to the objects in the array i maped. Something like this…

[
{
name: “string”
rating: [1,2,3,4,5]
}
]

Thanks for your explanation, I’ve finally gotten the logic

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.