Languages
[Edit]
EN

React - default property values in component

6 points
Created by:
Dirask JS Member
3460

In this article, we would like to show you how to set default property values in React component.

Quick solution:

const Component = ({ counter = 0 }) => {
  return (
    <span> {counter} </span>
  );
};

// Usage example:

<Component /> 

 

There are available two approaches how to do it, so check the below examples:

1. Using default properties

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:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const Component = ({ counter = 0 }) => {
  return (
    <span> {counter} </span>
  );
};

const App = () => {
  return (
    <div>
      <p>Component default counter value: <Component /></p>
      <p>The assigned counter value: <Component counter="3" /></p>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

2. Using defaultProps

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: 

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const Component = ({ counter }) => {
  return (
    <span> {counter} </span>
  );
};

Component.defaultProps = {
  counter: 0
};

const App = () => {
  return (
    <div>
      <p>Component default counter value: <Component /></p>
      <p>The assigned counter value: <Component counter="3" /></p>
    </div>
  );
};

const root = document.querySelector('#root');
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. 

ReactJS

React - default property values in component
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join