Search code examples
javascriptreactjsconditional-statementsuse-stateconditional-operator

React .map function not passing data to useState


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.


Solution

  • you have to use onClick like this

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