I have a component like this
const Row = () => {
const [isActive, setIsActive] = React.useState(false);
return (
<div
style={{
backgroundColor: isActive ? 'green' : '#c8c7c5',
}}
onClick={e => {
setIsActive(currentState => {
return !currentState;
});
}}
>
hello
</div>
);
};
I am using the component multiple times in another component like this
const ItemsArr= [
{
id: 'list-1',
component: <Row />
},
{
id: 'list-2',
component: <Row />
},
{
id: 'list-3',
component: <Row />
}
];
const [listItems, setListItems] = React.useState(ItemsArr);
For component Row, I am clicking on it and background color changes. when I click again, background color changes back to original. This is working fine.
What I want to do is, when I click on component Row all other selected Row components background should be removed, so that the one I select, that only should have the background.
Can someone please help me with this?
you need to have separate flag for each items. For Example you can refer below snippet.
You need to check the index then assign value to that flag
const tempData = [...arryData];
tempData[index] = {
...tempData[index],
isActive: value,
};
setState(tempData);
I hope this would be helpful, thanks.
export const Row = () => {
return (
<div >
hello
</div>
);
};
This is how you can set the background color row:
const ItemsArr= [
{
id: 'list-1',
component: <Row />
},
{
id: 'list-2',
component: <Row />
},
{
id: 'list-3',
component: <Row />
}
];
const [listItems, setListItems] = React.useState(ItemsArr);
<div>
{listItems.map((item, index) => (
<div onClick={() => setIsActive(index)} style={{
backgroundColor: index === isActive ? 'green' : '#c8c7c5',
}}>
{item.component}
</div>
))}
</div>
You can do like this
const Row = ({id, isActive, onClick}) => {
return (
<div
style={{
backgroundColor: isActive ? 'green' : '#c8c7c5',
}}
onClick={()=>onClick(id)}
>
hello
</div>
);
};
export default function App() {
const ItemsArr= [
{
id: 'list-1',
component: Row
},
{
id: 'list-2',
component: Row
},
{
id: 'list-3',
component: Row
}
];
const [activeID, setActiveID] = React.useState("");
const [listItems, setListItems] = React.useState(ItemsArr);
return (
<div className="App">
{listItems.map(item=>(
<item.component id={item.id} isActive={item.id === activeID} key={item.id} onClick={setActiveID} />
))}
</div>
);
}