How to specify Default Props in React.js?

What is a Lifecycle Method in React.js? »

If you remember in the previous tutorial you learnt how to show a loading screen with the text “Loading…” when the components are being loaded by the React server. You can of course customize this loading text and use something else by passing it as props. In the render() method of App component in the index.js, make the following changes:

if (!this.state.hrs){
    return <Loader loadingText="Loading info..." />;
}

And inside Loader.js, make the following changes:

import React from 'react';

const Loader = (props) => {
    return (
       <div className="ui active dimmer">
           <div className="ui big text loader">{props.loadingText}</div>
       </div>
    );
}

export default Loader;

Now, you may use the Loader component in multiple places, not just in App component. So, what happens if you forget to provide a text (loadingText) to the Loader component?

       if (!this.state.hrs){
           return <Loader />;
       }

Of course, you won’t be getting any text while the component is being loaded.

This is probably not the best idea to only show some content when the user provides something. There should be some way to show some default value in case the user forgets to provide any value in the form of props. There are two ways to provide a default text.

Using || operator

You can use an or symbol || to specify a default value along with the originally passed value:

const Loader = (props) => {
    return (
       <div className="ui active dimmer">
           <div className="ui big text loader">{props.loadingText} || Loading info...</div>
       </div>
    );
}

Using Default Props

Using {props.loadingText} || Loading info… at multiple places could be a bit clumsy. Therefore, you can specifically tell React to use certain default values when values for some props are not found. Inside Loader.js, add a new object as follows:

import React from 'react';

const Loader = (props) => {
    return (
       <div className="ui active dimmer">
           <div className="ui big text loader">{props.loadingText}</div>
       </div>
    );
}

Loader.defaultProps = {
    loadingText: "Loading info..."
};

export default Loader;

So, you’re adding a new object called defaultProps on top of Loader component which will use default values for the props listed inside of it. Now, if values are not passed to props.textLoading, then these defined values will be used instead.

Leave a Comment