Search code examples
reactjsconditional-rendering

ReactJs - Conditional Rendering or hiding component


What's the de facto approach to choosing between conditional rendering or hiding the component with { display: 'none' }?

For the sake of discussion, let's say that I have a FilterComponent that holds the title of the filter, and a list of FilterItems, with name and amount.

In short, a FilterComponent could be:

Color

  • Blue (19)

  • Yellow (17)

  • Orange (3)

  • Black (7)

  • Green (10)

    + Show More

When hitting Show More button, more FilterItems will be displayed, i.e.

Color

  • Blue (19)

  • Yellow (17)

  • Orange (3)

  • Black (7)

  • Green (10)

  • Brown (17)

  • Pink (88)

  • White (55)

  • Red (32)

  • Purple (17)

    - Show Less

Should I hide the FilterItems that are below the Show More? Or should I return null for those below and render them after updating the state with Show More?


Solution

  • I think there are a few ways to accomplish what you need. However, this seems to be the most practised:

    {myConditionIsTrue && <MyComponent />}
    

    In your case, it makes sense to use state. I would have a prop inside FilterComponent called showFullList

    {this.state.showFullList && (
     <React.Fragment>
       <All/><The/><Other/><Components/>
    </React.Fragment>)}
    

    Just be weary, this mechanism is actually removing/adding to the DOM.