Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Brandon Benefield
Brandon Benefield
7,739 Points

React conditional rendering

I'm trying to recreate the most basic version of the RSVP react app that Guil Hernandez walks us through in the Learn React track here on treehouse. Now by basic I'm talking about whether or not a div should render. Kind of like filtering the guests depending on if they are attending or not in the rsvp app.

In this version, I have two divs. One is red, the other is blue. I want them to render depending on the value of shouldRender.

I've tried everything I can think of but I can only either:
1) Get both of them to render
2) Get nothing to render

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {
    div: [
      {
        color: 'red',
        shouldRender: true
      },
      {
        color: 'blue',
        shouldRender: false
      }
    ]
  };

  render() {
    return (
      <div className="contain">
        {
          this.state.div.map((foo, index) => 
            <div className={foo.color} key={index}></div>
          ).filter(bar => bar.shouldRender === true)
        }
      </div>
    );
  }
}

export default App;

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

In your example filter should come before map. map() changes the items in an array into something else so after the map call you have an array of <div> elements, not the object you have in state. Because they don't have a shouldRender property anymore, they would all be filtered out.

Brandon Benefield
Brandon Benefield
7,739 Points

Thank you so much. This just shows me that I need some more practice with map() filter() and reduce().