skip to Main Content

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


  1. 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:

    {pages.map((page, idx) => (
      <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
        <Photo onClick={() => { /* your onClick handler here */ }} />
        <p css={CSSPageContent}>{page.text}</p>
    ........
      </li>
    ))}
    

    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.

    Login or Signup to reply.
  2. Add onClick func as prop in Photo component.

    {pages.map((page, idx) => (
      <li key={page.page_id} id={`${idx + 1}`} css={CSSCarouselItem}>
        <Photo onClick=(() => {/* your click func */})/>
        <p css={CSSPageContent}>{page.text}</p>
    ........
      </li>
    ))}
    

    And add the attribute for your img (or what you have there)

    function Photo({onClick}) {
       <img onClick={onClick}/>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search