ryanve
ryanve

Reputation: 52521

Difference between React defaultProps and inline props

What (if any) is the functional difference between these? In both cases the spread props override the preset props. What reasons would there be to use one syntax over the other?

1. default props

const Input = (props) => (
  <input {...props} />
);

Input.defaultProps = {
  className: "input",
};

2. inline props

const Input = (props) => (
  <input className="input" {...props} />
);

Upvotes: 1

Views: 561

Answers (1)

Panther
Panther

Reputation: 9408

You can use defaultProps when, your component needs certain props to operate, but you are not sure if you would get it at all times. So you provide a default value for it. This will be set if your actual props is not present.

Your spread operator expands(or spreads) the given object. Each key, value pair is passed as prop to the component. You would use this in cases, where you are not sure of the props, your child component requires. So just spread it out and let the child use what it needs. (This is just once scenario)

In your question, you have mentioned that spread operator overrides the present props in both cases. The overriding behaviour is because of the position of spread operator and not because of use defaultProps or absence of the same.

So lets assume the below code. Here, input would receive myClass as prop in className. Because you are spreading the props after className in input.

const props = {
 className: 'myClass',
};

<input className="input" {...props} />

While in the below code, input would receive input as prop in className.

const props = {
 className: 'myClass',
};

<input {...props} className="input" />

Upvotes: 2

Related Questions