Default Prop values React JS component

React JS

Default Prop values are set whenever no value is set to the prop of the React component. We may not set all props values while loading component or sometime it may not be feasible to set each and every props value of the component. Or let’s say we have a props whose value is certain value in most of the cases. But for some cases, the value may be different. In such cases, it may feasible or good practice to set props value manually, only in the exception cases. And set the default value in all other cases.

We can accomplish this by assigning to the special defaultProps property

import PropTypes from 'prop-types';

class MyComponent extends Component {
 render(){
    return (
      <h1>{this.props.message}</h1>
    )
  }
};

MyComponent.propTypes = {
  message: PropTypes.string
};

MyComponent.defaultProps = {
  message: 'Hello World' 
};

You May Also Like