Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS defaultProps empty function declaration

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,
};
like image 862
dmraptis Avatar asked Jan 03 '19 16:01

dmraptis


People also ask

How do you set a default prop in a function?

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.

Is Empty function in JavaScript?

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.

How do I set a default prop in React?

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.

How do you define default values for props input to a React component?

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.


2 Answers

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.

like image 147
Anas Avatar answered Sep 23 '22 06:09

Anas


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.

like image 28
canecse Avatar answered Sep 25 '22 06:09

canecse