Check if a Prop was passed to a component in React

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

Check if a Prop was passed to a component in React #

To check if a prop was passed to a component in React:

  1. Compare the prop to undefined.
  2. If the prop is equal to undefined, it wasn't passed to the component.
  3. Otherwise, it was passed.
App.js
const Button = ({withIcon}) => { if (withIcon !== undefined) { console.log('prop was passed'); } else { console.log('prop was NOT passed'); } return <button>Click {withIcon ? '▶️' : null}</button>; }; export default function App() { return ( <div> <Button /> </div> ); }

The Button component takes a withIcon prop.

If a prop isn't passed to a component, it's value will be undefined.

Inside of our JSX code, we can use a ternary operator to check if the prop was passed to the component.

The ternary operator is very similar to an if/else statement.

It checks if the value to the left of the question mark is truthy, and if it is, the operator returns the value to the left of the colon, otherwise the value to the right is returned.

You could also use the logical AND (&&) operator to check if a prop was passed in your JSX code.

App.js
const Button = ({withIcon}) => { if (withIcon !== undefined) { console.log('prop was passed'); } else { console.log('prop was NOT passed'); } return <button>Click {withIcon && '▶️'}</button>; };

The logical AND (&&) operator returns the value to the right if the value to the left is truthy.

We can use this approach because booleans, null and undefined are ignored. They simply don't render.

The following JSX expressions all render nothing.

App.js
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>

If you need to check if a prop was passed to a component outside of its JSX code, compare the prop to undefined.

App.js
const Button = ({withIcon}) => { if (withIcon !== undefined) { console.log('prop was passed'); } else { console.log('prop was NOT passed'); } return <button>Click {withIcon && '▶️'}</button>; };

If the prop is equal to undefined, then it wasn't passed to the component, unless, the parent component explicitly passed an undefined value for the prop, which is pretty much the same.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.