Home > Mobile >  React .map function not passing data to useState
React .map function not passing data to useState

Time:01-22

Why is my setSelected useState not accepting the data from the .map function? I have the following react js code:

    const [ selected, setSelected ] = useState(null)
    const sectionItems = [
        { id: "1", title: "title1", description: "description1" },
        { id: "2", title: "title2", description: "description2" },
        { id: "3", title: "title3", description: "description3" },
    ]

I am mapping through the sectionItems and rendering a modal, based on if selected has an item or not:

{sectionItems.map((section, index) => {
                    return (
                        <div key={section.id} className="processSection1" onClick={setSelected(section) >
                            <div className="processTitle" >{section.title}</div>
                        </div>
                    )
                })}


{selected ? <Modal title={selected.title} description={selected.description}  /> : " "}

Problem: Why cant I pass the data into setSelected? Or the more precise question is, how can I render the modal with each sectionItem? Also am getting this error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

CodePudding user response:

you have to use onClick like this

onClick={()=>setSelected(section)}

CodePudding user response:

If you want to add a value to a function you should use an inline function inside the onClick. Right now you are triggering the function for each rendering at render time.

Change:

onClick={setSelected(section)}

to:

onClick={() => setSelected(section)}
  •  Tags:  
  • Related