EN
React - default property values in component
6 points
In this article, we would like to show you how to set default property values in React component.
Quick solution:
xxxxxxxxxx
1
const Component = ({ counter = 0 }) => {
2
return (
3
<span> {counter} </span>
4
);
5
};
6
7
// Usage example:
8
9
<Component />
There are available two approaches how to do it, so check the below examples:
This approach is the most common and currently recommended (ES6). We are using here assigning default values to the properties of a function component.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Component = ({ counter = 0 }) => {
6
return (
7
<span> {counter} </span>
8
);
9
};
10
11
const App = () => {
12
return (
13
<div>
14
<p>Component default counter value: <Component /></p>
15
<p>The assigned counter value: <Component counter="3" /></p>
16
</div>
17
);
18
};
19
20
const root = document.querySelector('#root');
21
ReactDOM.render(<App />, root);
Instead, this approach uses the built-in defaultProps
functionality, which is less recommended.
Note:
According to the developers of React, this functionality will be discontinued.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const Component = ({ counter }) => {
6
return (
7
<span> {counter} </span>
8
);
9
};
10
11
Component.defaultProps = {
12
counter: 0
13
};
14
15
const App = () => {
16
return (
17
<div>
18
<p>Component default counter value: <Component /></p>
19
<p>The assigned counter value: <Component counter="3" /></p>
20
</div>
21
);
22
};
23
24
const root = document.querySelector('#root');
25
ReactDOM.render(<App />, root);
Note:
Main disadvantage of that solution is necesssity to add to each component additional code that generates overhead and effort for programmers.