Search code examples
javascriptreactjs

How to expose a "param" like React does in onChange, onClick, etc.?


I want to do what React does with onClick, onChange, etc.

React does:

onClick={(event)=>console.log(event)}

I want to do:

someProp={(wanna_do_this)=>console.log(wanna_do_this)}

Solution

  • You just have to create a prop named as you want and pass it. For example:

    import PropTypes from 'prop-types';
    function CalledComponent ({onCustom}){
       // Here you'll be able to call this custom event/function.
       // Let's say I call it in useEffect.
       useEffect(onCustom, []);
       // Or maybe I call it in many events at the same time.
       return (<div onClick={onCustom} onHover={onCustom}>
             I'm called and I execute custom events when I'm clicked or hovered :D
       </div>);
    }
    // PropTypes stuff.
    CalledComponent.propTypes = {
       onCustom: PropTypes.func,
    };
    

    So later I could simply call it and pass a function to it.

    function ComponentThatCalls(){
        return (<CalledComponent onCustom={(e)=>console.log(e.target.value)}/>);
    }