What is the best practice defining a function defaultProps
that is empty in ReactJS?
My solution so far is either an empty arrow function or a null value. Which way would be better?
MyComponent.defaultProps = {
onClick: () => {},
onClickNull: null,
};
You can use props to send data to a component. Like default values for function arguments, props also have default values. defaultProps can be defined as a property on the component class itself to set the default props for the class. defaultProps is used for undefined props, not for null props.
The empty statement is a semicolon ( ; ) indicating that no statement will be executed, even if JavaScript syntax requires one. The opposite behavior, where you want multiple statements, but JavaScript only allows a single one, is possible using a block statement, which combines several statements into a single one.
The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.
You can define default values for your props by assigning to the special defaultProps property: class Greeting extends React. Component { render() { return ( <h1>Hello, {this.props.name}</h1> ); } } // Specifies the default values for props: Greeting.
I don't think there is a right answer for this.
If you want to be more explicit in your code, go with the null
and check if the function is null
before calling it.
If you want to have less code, go with empty function.
The more important thing I would say, is to be consistent in the entire project.
Important thing to keep in mind is that an empty function ()=>{}
is an object hence its truthy whereas null
and undefined
are falsy.
So if you want to check whether that event handler prop is passed on implementation and handle both cases (supplied and not supplied) differently, it makes more sense to go with null
or undefined
.
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