Where is this (default) prop coming from?

By Bernie FitzGerald •  Updated: 03/02/22 •  3 min read

This post is just a quick refresher for the times when you might find yourself mystified as to where a component is getting a certain prop.

Typically, the parent component will pass down props to the child as HTML like attributes when rendering the child. For example, let’s look at an App component acting as the parent who is rendering a child component named MyPropHeavyComponent:

function App() {
 return (
    <div>
      <MyPropHeavyComponent id='12' firstName='Bernie' lastName='Danger' />
    </div>
  );  
}

So how does the child component know how to work with these props?

Let’s look at the child component:

export default function MyPropHeavyComponent(props) {
	return (
		<div>
			<h2>First Name</h2>
			<p>{props.firstName}</p>
			<h2>Last Name</h2>
			<p>{props.lastName}</p>
		</div>
	);
}

We can see that our component definition now has props as a parameter. This parameter contains a key for each of the props passed down. So you can access the firstName prop via props.firstName. So the above component just renders two headers and their data accordingly. Simple so far but are there other ways you might encounter props?

Let’s take a quick look at default props. Default props are variables whose data you want to set in case the parent component hasn’t passed that prop to the child.

In the above example, we might be building a form for employees and if we don’t get the employee’s role as a prop we want to display Undisclosed instead.

In this case, we could set a default prop for role and set its value to Undisclosed.

Our component might then look like this:

export default function MyPropHeavyComponent(props) {
	return (
		<div>
			<h2>First Name</h2>
			<p>{props.firstName}</p>
			<h2>Last Name</h2>
			<p>{props.lastName}</p>
			<h2>Role</h2>
			<p>{props.role}</p>
		</div>
	);
}

MyPropHeavyComponent.defaultProps = {
	role: 'Undisclosed'
}

If we render this component and don’t pass a role prop to the child:

<MyPropHeavyComponent id='12' firstName='Bernie' lastName='Danger' />

Our App will render:

The app using a default prop

If we pass a role of value Engineer into the child:

<MyPropHeavyComponent id='12' firstName='Bernie' lastName='Danger' role='Engineer' />

Our app will render this:

Our app with the default prop overridden by being passed to the child component

It’s always important to remember that if you see a prop being used in a component and you can’t find that prop in the parent, then it is likely to be a default prop.

Bernie FitzGerald