Reputation: 37
i am studying React and Material UI and I am trying to change the background color of the clicked div, for the moment they changed all.
I would like to change the background color from white to lightblue when one of the div is clicked and back to white only when we click on the other div. I am getting the datas from a JSON file. I hope it make sense.
I will share my code.
<Grid sx={{ display:'flex' }} >
{ props.supplies.map((supply,id) => {
return(
<Grid onClick={changeBackground} lg={4} key={id} sx={{ marginRight:"0.8rem", backgroundColor:`${background}`, border:2, borderRadius:2, borderColor:'#ddedf4', padding:'5px 8px 25px 25px' }}>
<RadioGroup
name={supply.months}
onChange={handleChange}
value={value}
>
<FormControlLabel value={ supply.months } control={<Radio size="small"/>} label={ <Typography fontSize='14px'>{supply.months}</Typography> } />
<Typography marginLeft='30px'>{ supply.boxes }</Typography>
</RadioGroup>
</Grid>
)
})}
</Grid>
This code will render 3 divs with a checkbox and some text with a white background color from white to lightblue
const[background,setBackground] = useState('white')
const handleChange = (e:React.ChangeEvent<HTMLInputElement>) =>
console.log(e.target.value)
const changeBackground = () => setBackground('lightblue')
When i click on a div they all change background color.
Can someone help me to understand the problem, i am still a beginner.
Have a good day
Upvotes: 1
Views: 2496
Reputation: 9
in your code,
// in your code
// css
.change_background{
background-color:'violet'
}
<Grid sx={{ display: 'flex' }} >
{props.supplies.map((supply, id) => {
return (<Grid onClick={e=>e.currentTarget.classList.add('change_background')} lg={4} key={id} sx={{ marginRight: "0.8rem", backgroundColor: `${background}`, border: 2, borderRadius: 2, borderColor: '#ddedf4', padding: '5px 8px 25px 25px' }}>
<RadioGroup name={supply.months} onChange={handleChange} value={value}>
<FormControlLabel value={supply.months} control={<Radio size="small" />} label={<Typography fontSize='14px'>{supply.months}</Typography>} />
<Typography marginLeft='30px'>{supply.boxes}</Typography>
</RadioGroup>
</Grid>
)
})}
</Grid>
Hope it works
Upvotes: 0
Reputation: 220
You should maintain a state of the <div>
index. The map()
function provides you with an index argument (doc here). In your case, its id
In your Grid onClick function, change the state to its index, and style it conditionally.
const [state, setState] = useState(-1);
map((data, index) => (
<Grid
onClick={() => setState(index)}
style={{
background: state === index ? 'lightblue' : 'white'
}}
>
))
Upvotes: 2