defaultProps in ReactJS

As we know, passing props to a component is same as the passing parameters to function.
In function, you can have default parameters. Just like default parameters, a component can have defaultProps.

Let us have a look at an example to know how to provide defaultProps.


import React from 'react';

const Greetings = (props) => {
  return(
    <div>
      Hello, {props.name}
      <br/>
      <br/>
      <button onClick={e=>{props.sayHello(props.name)}}>Say Hello Outloud</button>
    </div>
  );
};

// Component type doesn't matter. stateful or stateless
// componentName.defaultProps
Greetings.defaultProps = {
    name: "Learner"
};

class Parent extends React.Component{
    constructor(props){
        super(props);
        this.onHello = this.onHello.bind(this);
    }
    onHello(name){
        alert(`Hello ${name}`);
    }
    render(){
        return (
            <div>
                <Greetings sayHello={this.onHello} />
            </div>
        );
    }
}

ReactDOM.render(
    <Parent />,
    document.getElementById('root')
);
                    

Open above code in codepen.

As per above code, you can add defaultProps by adding <ComponentName>.defaultProps.
In above code, we have not pass name property to Greetings component but name property is added in defaultProps of Greetings component. So value of name is "Learner".

In example, we have used stateless component. We can provide defaultProps to stateful component in same way.

Conclusion

In this section, we have learned about defaultProps of component in ReactJS.
In the next section, you will learn about PropTypes of component in ReactJS.