Conditional rendering of components
Usually when building complex UIs, you would need to render a component or a React element according to the state or props received.
React components allow JavaScript to be executed within curly brackets and it can be used with the conditional ternary operator to decide which component or React element to render. For instance:
const Meal = ({ timeOfDay }) => ( <span>{timeOfDay === 'noon' ? 'Pizza' : 'Sandwich' }</span> )
This also could have been written as:
const Meal = ({ timeOfDay }) => ( <span children={timeOfDay === 'noon' ? 'Pizza' : 'Sandwich' } /> )
If passing "noon"
as the timeOfDay
property value, it will generate the following HTML content:
<span>Pizza</span>
Or the following when the timeOfDay
property is not set to "noon"
:
<span>Sandwich</span>
Getting ready
In this recipe, you will build a component that that renders one of its children...