← Back to React Course | Chapter 3: Components & Props | Lesson 9 of 11

Conditional and Optional Props

Optional props are like toppings on a pizza -- some are required for it to count as a pizza, and others you can leave off entirely.

Handling an Optional Prop

A prop is optional simply by not requiring the caller to pass it -- inside the component, you check whether it exists before using it, often with a default value or a conditional check. This lets a component adapt its behavior based on what was actually provided.

Note: Combine optional props with default values so you don't need repetitive if checks throughout the component.

Warning: Accessing a property on an optional prop that might be undefined (like props.user.name when user wasn't passed) will throw an error.

Example: Handling an Optional Prop

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function UserGreeting({ name, subtitle }) {
      return (
        <div>
          <h2>Hello, {name}!</h2>
          {subtitle && <p>{subtitle}</p>}
        </div>
      );
    }
    function App() {
      return <div><UserGreeting name="Sam" subtitle="Welcome back" /><UserGreeting name="Alex" /></div>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Conditionally Rendering Based on Props

A component can change what it renders depending on which props were passed in, using the same conditional rendering techniques (ternaries, &&) covered earlier. This is especially useful for components that show slightly different UI in different situations, like a logged-in vs logged-out state.

Note: Keep conditional rendering logic readable by extracting complex conditions into a named variable before the return statement.

Warning: Deeply nested conditional rendering inside JSX quickly becomes hard to read -- consider early returns for very different states.

Example: Conditionally Rendering Based on Props

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function StatusMessage({ isError, message }) {
      if (isError) {
        return <p style={{color: "red"}}>Error: {message}</p>;
      }
      return <p style={{color: "green"}}>{message}</p>;
    }
    function App() {
      return <div><StatusMessage isError={true} message="Failed to load" /><StatusMessage isError={false} message="All good" /></div>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Optional Props with Fallback Content

Sometimes an optional prop should show alternate fallback content rather than nothing at all when it's missing. The ternary operator works well here, letting you render one thing when the prop is present and something else when it isn't.

Note: Use props.value ?? 'default text' (the nullish coalescing operator) as a concise way to supply fallback content for missing values.

Warning: Using || instead of ?? for fallbacks can misfire on legitimate falsy values like 0 or an empty string.

Example: Optional Props with Fallback Content

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
    function ProfileBio({ bio }) {
      return <p>{bio ? bio : "This user hasn't written a bio yet."}</p>;
    }
    function App() {
      return <div><ProfileBio bio="I love building with React." /><ProfileBio /></div>;
    }
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Common Mistakes
  1. Marking a prop as required with PropTypes/TypeScript but still writing code that assumes it might be missing.
  2. Not providing a fallback for an optional prop, causing a crash when it's accessed but undefined.
  3. Making every single prop optional even when some genuinely must always be provided for the component to make sense.
Chapter Summary
  • Not every prop a component accepts needs to be required.
  • Optional props should have sensible defaults or safe fallback handling.
  • Conditional logic inside a component often depends on whether an optional prop was provided.
  • Clearly distinguishing required vs optional props makes a component easier to use correctly.
Browser Support

No browser-specific restrictions -- optional props rely on standard JavaScript conditional logic.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.