I’m student studying of react.
While working on the project, I had a question.
{pages.map((page, idx) => (
<li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
<Photo onClick={() => console.log('click!')}/>
<p css={CSSPageContent}>{page.text}</p>
........
</li>
))}
and Photo components
interface PhotoProps {
.....
onClick?: () => void;
}
const Photo = ({ src, width, height, blur, custom, onClick, text, placeholder }: PhotoProps) => {
return (
<div
onClick={onClick}>
...
</div>
I have to apply onClick handler only to Photo components.
However, onClick applies only to the highest element(li components) that is mapped.
photo’s onClick doesn’t work.
Is this inevitable?
Thank you for reading it.
2
Answers
No, you can apply the onClick handler to the specific component within the mapped element. To do that, you can simply pass the onClick handler to the Photo component inside the li element:
This way, the onClick handler will be passed to it, and inside component you can apply this on it’s parent component. And it can be triggered when the Photo component is clicked.
Add onClick func as prop in Photo component.
And add the attribute for your img (or what you have there)