Defining a default prop value in React

How to set a default prop value in a component.

We’ll use a basic header component as a base:

const Header = (props) => {
  return (
    <header>
       <h1>{props.title}</h1>
    </header>
  )
}

export default Header

When we use the component in our app we’ll need to set a title prop, if we don’t (as below) then nothing will display in our page:

import Header from './components/Header'

function App() {
  return (
    <div className="container">
      <Header />
    </div>
  );
}

export default App;

We can define the default prop value after the header component function (but in the same file):

const Header = (props) => {
  return (
    <header>
       <h1>{props.title}</h1>
    </header>
  )
}

Header.defaultProps = {
  title: "Default title"
}

export default Header

The default value will be used when the prop is defined in the component call: