[SOLVED] onClick function not working in child of function reactjs

Issue

This Content is from Stack Overflow. Question asked by amryann

I’m looking to make an onClick function that works in the child of my function, but it doesn’t seem to be working and I don’t know why.

The onClick is meant to take the id from this:

const userCampaigns = [
{
    id: "curse-strahd",
    title: "Curse of Strahd",
    image: "/card-images/affroen and friends.jpg",
    description: "Scary vampire man does evil."
},

and return the results from this in one of my components:

const sesssions = {

"curse-strahd": [
    "session1",
    "session2",
    "session3",
    "session4"
]

Then make a card that displays the sessions.

These are my components:
enter image description here

My code:

export default function ChooseCampaign() {
const [show, setShow] = useState(false);
const [displaySessionListId, setDisplaySessionListId] = useState("")

function clickHandler(displayId) {
    return () => {
        setDisplaySessionListId(displayId)
        setShow(!show)
    }
}

return <div style={{backgroundSize: 'cover', backgroundImage: `url(${imgCaravan})`, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'fixed', top: 0, width: '100%', height: '100%', marginLeft: '-8px' }}>
    <UserCampaignsList>
        {userCampaigns.map((val) => (<ChooseCampaignCard onClick={clickHandler(val.id)} key={val.id} id={val.id} image={val.image} title={val.title} description={val.description}/>))}
    </UserCampaignsList>
    <SessionCard sessionListId={displaySessionListId} />
</div>

}



Solution

Change onclick event call to below arrow function:

{userCampaigns.map((val) => (<ChooseCampaignCard onClick={()=>clickHandler(val.id)} key={val.id} id={val.id} image={val.image} title={val.title} description={val.description}/>))}

In clickHandler event, you are actually returning a function instead of executing statements. Either change your clickHandler function as below

function clickHandler(displayId) {
    setDisplaySessionListId(displayId)
    setShow(!show)
}

or call your click handler as below

<ChooseCampaignCard onClick={()=>clickHandler(val.id)()} key={val.id} id={val.id} image={val.image} title={val.title} description={val.description}/>


This Question was asked in StackOverflow by amryann and Answered by Mrudhula Katta It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?