I have a react functional component and I want to decide dynamically if I want to have an onClick handler on it, something like this:
const foo () => {
let add_onClick = true;
return (
<div *(if add_onClick ==true then add an onClick event)*/>
)
}
I think I can convert the component to a class, create a Ref for the component then add a click eventListener in componentDidMount, but is there a simpler way to do this?
If you keep in mind that:
let Foo = props => <div onClick={props.onClick} />
is really the exact same thing as:
let Foo = props => React.createElement('div', { onClick: props.onClick })
then it should be easy to see how you can optionally pass props. In JSX you can do:
let Foo = props =>
<div
{...(props.onClick ? { onClick: props.onClick } : {})}
/>
This is, of course, a little silly, in particular because you can always click on a div whether you handle it properly or not. A much better solution to your exact question would be to do something like:
let doNothing = {} => {}
let Foo = ({ onClick = doNothing }) => <div onClick={onClick} />
That way you if you forget to pass a click handler, you'll still handle it by default, but do nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With