It's common for a component to return different types of React elements based on its
props. React is extremely flexible in this regard — you can return entirely different content each time the component function is called. The only requirement is that render function returns a React node - this can be a React Element, a string, null, or an array of any of these.
Let's look at one of the most common cases: conditionally rendering a React element based on whether a specific
prop exists or not.
In this example, we'll render a Card component that takes a
title prop and optionally a
subtitle prop. We only want to render a
h2 for the subtitle if it exists.
For simple conditional rendering, we take advantage of the short-circuit evaluation of
&&. If the left-hand side of the
&& is falsy, the expression evaluates to the left hand side. Otherwise, the expression evaluates to the right-hand side.
In the example, when a
subtitle prop is not passed in explicitly, the value of the prop is
undefined, so the
&& expression evaluates to the left-hand side (
undefined). When React sees an
undefined value, it renders nothing. When we do pass a value for the
subtitle prop, the left-hand side is truthy, so the expression evaluates to the right-hand side — in this case, our
Note that an empty string
"" is falsy, but the expression will still evaluate to a string (not the boolean
false). If the parent component renders empty string children, this can affect rendering. So you may want to doubly negate the prop (i.e. convert to boolean) with
(!!subtitle && ...) to get the value
false (which doesn't render anything).
In this example, we define styles below where they are used in the component
render functions. This pattern is fairly common. Styles are often secondary to the component logic, so we want our logic to come first in the file.
This technique works because the
stylesvariable declaration is accessible at the beginning of the block it's defined in (the top level), and we assign a value to
stylesbefore the render functions are ever called.
Rendering with ternary
Let's look at another common case: rendering a different React element for when a
prop exists and when it doesn't. We can accomplish this easily with the ternary operator. It's common to render defaults this way.
For more complex rendering, we can introduce variables to store our React elements, letting us combine them in different ways.
Let's take a look at an example where the rendering is substantially different based on whether or not the
error props exist.
Rendering in React is powerful because the logic can be as simple or complex as we need it to be. However, as rendering complexity grows, the code can start to become unmanageable. Consider breaking down complex components into smaller, simpler ones for a more maintainable code base.