3

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?

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer. I'm a bit confused, what's wrong with the first answer? It seems if no click handler was passed, then no onClick will be attached. Why do I need to attack onClick and make it do nothing instead?
Ahh they're both fine, but the syntax for doing it in JSX sucks, and also I think it's better to always handle events if an event could be handled. Think about attaching propTypes.. an onClick propType sounds like a function to me, not an enum of undefined and function, does that make sense?
0

Try the following. onClick will be null unless your value is true:

<div onClick={add_onClick && () => {console.log("You clicked me!");}}></div>

Comments

0

You could do it like this as well

const foo = () => {
  let add_onClick = true;
  return (
    <div { ...add_onClick && { onClick: () => {} } }/>
  )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.