Link Search Menu Expand Document

Component Loops and Conditionals

Sometimes we wish to repeat chunks of JSX or to conditionally include/exclude JSX in a component.

In React we can transform collections of data into repeated JSX using the map function. JSX can be conditionally included using the boolean && operator and ternary statements.

Table of Contents

  1. Loop Da Loop With Map
  2. Country Explorer App
  3. React Countries App
  4. Conditional JSX - &&
  5. Conditional JSX - Ternary
  6. What’s Next?

Loop Da Loop With Map

Use map to create components from collections of data:

See the Pen Looping with Map React by Kyle Geske (@stungeye) on CodePen.

📢 Note: Components created with map must be assigned a unique key attribute.

It’s best to use database IDs for keys, but if IDs aren’t available use the map index as above.

Resources

Country Explorer App

Country Explorer App

A “World Countries” React app using:

  • Array of country data from the restcountries.eu API.
  • Country component that accepts props for a name, population, area, and flag image url.
  • App component that uses map to declare one Country component for each element in our country array.

📢 Note: Let’s agree not to worry about how the data loading works for now.

We’ll learn a more integrated approach to loading data in React in a later module.

Resources

React Countries App

Our shiny new Country App:

See the Pen React Countries Basic by Kyle Geske (@stungeye) on CodePen.

📢 Note:

  • Component styles are provided by MVP.css, which is a dependency of our codepen. There’s a small amount of additional CSS in the CSS tab.
  • The Country component leverages HTML details/summary elements for expandable content.
  • JSX elements can be declared across multiple lines as seen within App where a Country element spans three lines.

Conditional JSX - &&

We can optionally include JSX using a Boolean &&.

Let’s add an optional sup element for densely populated countries:

See the Pen React Countries Conditional JSX by Kyle Geske (@stungeye) on CodePen.

👆 Our first component with code above the return statement.

📢 Note: This technique works because true && expression always evaluates to expression, and false && expression always evaluates to false.

Resources

Conditional JSX - Ternary

Use a ternary to conditionally render different text or different components:

See the Pen React Countries Ternary Conditional JSX by Kyle Geske (@stungeye) on CodePen.

👆 The Region component will display “None” if region prop is an empty string.

Scroll to “Bouvet Island” to see this in action.

Resources

What’s Next?

You’ve now reviewed the basics of React.

In the next module you’ll learn more advanced React topics like:

  • Handling User Events
  • Maintaining Component State
  • Fetching JSON Data
  • Handling Form Input
  • Styling Components with CSS