Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS dynamically adding onClick event

Tags:

reactjs

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?

like image 490
David C Avatar asked Apr 08 '26 20:04

David C


1 Answers

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.

like image 118
azium Avatar answered Apr 11 '26 09:04

azium