skip to Main Content

I’ve got a third party library providing some React components whose functionality I want to extend by adding on onClick() handler function. The handler function works however I don’t know how to have this component listen for onClick() events and in turn trigger the handler at the expected time. The source code for the third party library is not available. Any suggestions? Thanks in advance!

I’ve searched around and found some mentions of passing the listener down to the base HTML element through props but I’m at a loss on how to do this if the ThirdParty source is not available.

Here what I’m working with:

import { ThirdPartyComponent } from "ThirdPartyLibrary"


function MyComponent() {

    return (<>
        <ThirdPartyComponent/>
    </>)
}

export default function LargerApp() {
    return (<>
        Lorem Ipsum
        <MyComponent
            onClick={(e) => { alert('onClick event handled successfully') }}
            ))
        />
        More text on the page
    </>)
}

2

Answers


  1. Here onClick is passed as props to your component :

    <MyComponent
                onClick={(e) => { alert('onClick event handled successfully') }}
                ))
            />
    

    Your functional component receives all props as a parameter:

    function MyComponent({onClick}) {
        // You can use your onClick function here
    
    
        return (<div onClick={onClick /* Depending on the structure of the component you could wrap it in a div and give the div the onClick */}>
            <ThirdPartyComponent onClick={onClick /*if the third Party component supports it you can pass it directly as a prop*/}/>
        </div>)
    }
    
    Login or Signup to reply.
  2. Here you can pass click event and any other event like this ….

    import { ThirdPartyComponent } from "ThirdPartyLibrary";
    
    const ExtendedThirdPartyComponent = (props) => {
      const { onClick, ...rest } = props;
    
      return (
        <ThirdPartyComponent {...rest} onClick={onClick}>
        </ThirdPartyComponent>
      );
    }
    
    export default function LargerApp() {
      return (
        <>
          Lorem Ipsum
          <ExtendedThirdPartyComponent
            onClick={(e) => {
              alert("onClick event handled successfully");
            }}
          />
          More text on the page
        </>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search