2
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.

Yash Sharma
  • 232
  • 2
  • 12

2 Answers2

3

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.

Piotr Żak
  • 2,046
  • 5
  • 18
  • 30
  • What is i here? – Yash Sharma Sep 04 '21 at 11:23
  • 1
    Ya, it worked. I was doing the same like you did but I was writing the conditional in a function defined outside of the map method and referencing the function name in the className. But, that was adding the className to all items. But, it worked after I wrote the conditional in ClassName like you did and it worked. Thanks for the help. I was stuck at this for the past 10 hours. – Yash Sharma Sep 04 '21 at 15:29
  • Where do you close the ``? – Mars2024 May 01 '22 at 17:59
  • There's only 1 ` backtick here – Mars2024 May 01 '22 at 17:59
0

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.

Jayanth
  • 27
  • 1
  • 5