Reputation: 232
const allTodos = [{id: 1, name: 'whatever user type'}, { }, { }, .... { }] // Defined as an array using setState in other file. Imported in this file as allTodos using props.
export const Todos = (props) => {
props.allTodos.map((prev) => {
return (
<div id="item_container">
<button type='button' className = 'check_button'
onClick = {() => setActiveTodos(prev.id)}>
<img src = {check} alt="" id = "check_img"></img>
</button>
<li id="li_item">{prev.name}</li>
</div>
)}
}
Now, the question is I want to add some specific style to the element(Button) clicked upon on. The styling I want to add is just change the background of the Button clicked upon. I tried using conditional to set className but the styling was added to every item. So, it didn't work out.
Upvotes: 2
Views: 1963
Reputation: 313
A very simple solution to this is using "Code Splitting". Just create a Button as a separate component and place the state inside the Button component.
const Button = ()=>{
const [ActiveTodos, setActiveTodos]=useState();
return (
<button type='button' className = 'check_button'
onClick = {() => setActiveTodos(prev.id)}>
<img src = {check} alt="" id = "check_img"></img>
</button>
);
}
export const Todos = (props) => {
props.allTodos.map((prev) => {
return (
<div id="item_container">
<Button />
<li id="li_item">{prev.name}</li>
</div>
)}
}
This will create seperate state for each item in the map so tha the styling can be applied only to a particular item.
Upvotes: 0
Reputation: 2132
conditional class - selecting particular class based on condition (in this case - if the activeTodos state == current index)
props.allTodos.map((prev, i) => {
<button type = 'button' key ={i}
className= {`${prev.id == activeTodos ? "active" : "inactive"}
onClick={e => setActiveTodos(prev.id)}}
</button>
}
There is some combinations (eg. There can be selected only 1 item per time or 4)
If You wan't 4 items selected (eg from 6) - then there is possiblity to hold active ids in array.
Upvotes: 3