Blog>
Snippets

Implementing Conditional Rendering in Sub Components

Showcases how to use conditional rendering within a sub component to display different UI elements based on the state or props, enhancing the interactivity of the data presentation.
function UserDetails(props) {
  return (
    <div>
      {props.isLoggedIn ? (
        <h1>Welcome back, {props.userName}!</h1>
      ) : (
        <h1>Please sign in.</h1>
      )}
    </div>
  );
}
This code snippet creates a functional component named 'UserDetails' that receives 'props'. It uses a ternary operator for conditional rendering based on the 'isLoggedIn' prop. If 'isLoggedIn' is true, it displays a welcome message with the user's name; otherwise, it asks the user to sign in.
function ProductList(props) {
  return (
    <ul>
      {props.products.length > 0 ? (
        props.products.map((product, index) => (
          <li key={index}>{product.name}</li>
        ))
      ) : (
        <li>No products found.</li>
      )}
    </ul>
  );
}
This code example defines a component called 'ProductList' which takes 'products' as a prop. It uses conditional rendering to either display a list of products or a message indicating that no products were found, depending on whether the 'products' array is empty.