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.
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>
}
CodePudding user response:
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}/>