← react hacks / react / using-defaultprops-for-default-props.md

Using defaultProps in React

Learn how to use defaultProps in React to set default values for your props. This post provides clear examples and explanations.

In React, defaultProps can be used to set default values for the props in a component. They are used when no value or undefined is supplied for a prop.

Here’s a basic example of how to use defaultProps:

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

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

In this example, if message prop is not provided while using MyComponent, it will default to ‘Hello, World!’.

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

The rendered HTML will be <h1>Hello, World!</h1> as ‘Hello, World!’ is the default value set for the message prop.

Remember, defaultProps are defined as a property on the component class itself, after the class declaration and using the same name as the component.

This feature is particularly useful in avoiding potential bugs due to undefined props and it improves code readability by providing an overview of the expected props.

Keep experimenting!

Quick hacks and tips from my daily workflow. Found this useful? Let me know.

@samuellawrentz →

$ ls ../react | head -4

More hacks

cd ../react →
  1. 3450e43 Enhancing Your Coding Experience with Neovim: A Beginner’s Guide

    tag: neovimtag: codingtag: productivity

  2. 9676c32 Understanding Neovim: How to Customize and Improve Your Text Editor

    tag: neovimtag: text-editortag: customization

  3. c52b973 Harnessing the Power of useRef Hook in React

    tag: reacttag: hookstag: useRef

  4. c2ffa3b Optimizing React Apps with useCallback

    tag: reacttag: useCallbacktag: optimization

00:00

This helps me increase the session time of my site. Thank you!

Can you stay a bit longer?