Last updated: Apr 7, 2024
Reading time·2 min
To check if a prop was passed to a component in React:
undefined
.undefined
, it wasn't passed to the component.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, its value will be undefined
.
Inside our JSX code, we can use the ternary operator to check if the prop was passed to the component.
The ternary operator is
very similar to an if/else
statement.
<button>Click {withIcon ? '▶️' : null}</button>
If the expression to the left of the question mark is truthy, the operator returns the value to the left of the colon, otherwise, the value to the right of the colon is returned.
You can imagine that the value before the colon is the if
block and the value
after the colon is the else
block.
If the withIcon
prop was passed to the component, the string is returned,
otherwise, null
is returned.
You could also use the logical AND (&&) operator to check if a prop was passed in your JSX code.
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.
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
if
statementIf you need to check if a prop was passed to a component outside of its JSX
code, compare the prop to undefined
.
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.