Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Child component onClick parameter doesn't work in parent component

I set button onClick as a parameter in the child component and drag and use onClick in the parent component.

The child component Room .

type Props = {
 items?: [];
 onClick?: any; 
}

const Room = ({ onClick, items: [] }: Props) => {

  return (
  <div>
    {items.length ? (
    <>
     {items.map((item: any, index: number) => {
      return (
       <>
         <button key={index} onClick={() => { console.log('hi'); onClick }}>{item.name}</button>
       </>
   )
  }
    </>    
  )
  </div>
 )
}

This is the parent component.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const LoadingRoom = () => {

const handleWaitingRoomMove = (e: any) => {
      e.preventDefault();
      console.log('Hello Move')
    }


  return (
  <>
    <Room
     items={[
           {
              name: "Waiting Room",
              onClick: {handleWaitingRoomMove}
            },
            {
              name: "Host Room",
            },
  ]}
  >
     
    </Room>
  </> 
)
} 

I want to call parent component’s onClick handleWaitingRoomMove but it’s not getting called.

However, console.log(‘hi’) on the button is called normally whenever the button is clicked. Only button is not called. Do you know why?

>Solution :

onlick is a attribute to the child element. so move it outside of the items array

 <Room
    
     onClick={handleWaitingRoomMove}
     items={[
           {
              name: "Waiting Room",
            },
            {
              name: "Host Room",
            },
  ]}
  >

In the child, missing () for onClick

onClick={(ev) => { console.log('hi'); onClick(ev) }}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading