I'm looking to re-render a specific portion of this component, (within the .map of my JSX), depending on which value of my optionObject is set to true.
Any ideas as to where I'm going wrong would be greatly appreciated-- still kinda new to React/functional components.
const [optionObject, setOptionObject] = useState(
{
'one' : false,
'two' : false,
'three' : true,
}
)
function switchOption(selectedOption) {
var objectCopy = optionObject;
for (const [key, value] of Object.entries(objectCopy)) {
if (key !== selectedOption) {
objectCopy[key] = false;
}
else {
objectCopy[key] = true;
}
}
setOptionObject(objectCopy);
}
return (
<>
<div className={styles.browseOptions}>
<div onClick={()=>switchOption(1)} className={`${styles.option} ${optionObject['one'] ? styles.active : ''}`}><h3>One</h3></div>
<div onClick={()=>switchOption(2)} className={`${styles.option} ${optionObject['two'] ? styles.active : ''}`}><h3>Two</h3></div>
<div onClick={()=>switchOption(3)} className={`${styles.option} ${optionObject['three] ? styles.active : ''}`}><h3>Three</h3></div>
{multi_grid_tiles_data?.map((grid, i) => {
if (optionObject[grid['parent']['name']])
return (
<div key={"gridList-"+i}>
<GridList grid_data={grid_data}/>
</div>
);
})}
</>
);
change
var objectCopy = optionObject;
to
var objectCopy = {...optionObject};
As the former doesn't copy an object, it just points to the existing object reference, therefore its the same object. The latter creates a new object reference and spreads the old contents into it.
In order for your component to rerender based on objects being updated in state, it has to be a new object reference. (same for arrays)