2

I have a component that might or might not recieve an onClick prop. I want to attatch this non-required prop as a click handler.

const MyComponent = (props) => {
    let {onClick} = props;

    return (
        <div onClick={onClick}></div>
    );
}

Whats the safest way to do this sort of thing if I don't know if the handler will be given?

MarksCode
  • 8,074
  • 15
  • 64
  • 133

1 Answers1

4

Using spread and ternary operator:

const MyComponent = ({ onClick, ...rest }) => {
  const props = onClick ? { onClick } : {}

  return <div { ...props } />
}
Jordan Enev
  • 16,904
  • 3
  • 42
  • 67
  • Sorry, I actually have other props in this component. I just took them out to simplify the question. How would I do this when theres other props involved? – MarksCode Jun 12 '18 at 00:11
  • In `rest` variable, you have all others props. – Jordan Enev Jun 12 '18 at 00:14
  • Also if you want explicitly describe the props as we did it for onClick, you can define them conditionally as here: https://stackoverflow.com/a/50367186/4312466 – Jordan Enev Jun 12 '18 at 00:18
  • Can I just do this instead? `onClick = onClick || null` then set the `onClick={onClick}`? – MarksCode Jun 12 '18 at 00:18
  • I'm not sure whether setting a `null` handler will cause an error. If so, you can pass an empty function, but in both cases you're setting a value to `onClick`. So I prefer the way I answered you. – Jordan Enev Jun 12 '18 at 00:30