Reputation: 1254
I want my Button component to only handle onClick
events if a callback function is passed to the component. I have two approaches for this, but I do not know which approach is better.
Approach 1 - Bind handleClick
with this.handleClick
or false
in the constructor, and pass handleClick
to onClick
in the render method.
class Button extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
onClick: PropTypes.func
};
static defaultProps = {
onClick: undefined
};
constructor(props) {
super(props);
this.handleClick = (props.onClick) && this.handleClick.bind(this);
}
handleClick() {
const { onClick } = this.props;
onClick();
}
render() {
const { children } = this.props;
return (
<Wrapper onClick={this.handleClick}> // False if onClick is undefined
{children}
</Wrapper>
);
}
}
Approach 2 - Bind handleClick
in the constructor and pass handleClick
or false
in the render method.
class Button extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
onClick: PropTypes.func
};
static defaultProps = {
onClick: undefined
};
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { onClick } = this.props;
onClick();
}
render() {
const { children, onClick } = this.props;
return (
<Wrapper onClick={(onClick) && this.handleClick}>
{children}
</Wrapper>
);
}
}
Upvotes: 1
Views: 547
Reputation: 5118
I think it's a matter of preferences since both cases are almost equal.
If you choose Approach 1 you would be saving space in memory (conditionally) because this.handleClick
would be a small value for cases in which props.onClick
is undefined
or false
, in the second approach you would be always setting the function which takes a little more space (however, this space is depreciable for me).
Approach 2 is more commonly used, people usually binds the function in the constructor without any condition and validates the call in the property that's needed.
Just as a side note, there is a third approach you could use which is to define an arrow function in the onClick
prop, I don't really use this one that much but just wanted to mention it.
You can learn more about passing functions to components in react docs
Upvotes: 1