Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 874
fasaas Avatar asked Nov 22 '18 13:11

fasaas


2 Answers

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.

like image 121
Neal Avatar answered Sep 18 '22 14:09

Neal


Generally in React it is better to not render something than to render it as hidden. Here is one related discussion: https://discuss.reactjs.org/t/conditional-rendering-or-toggling-hidden-classes/2535/6

like image 32
Ryan Cogswell Avatar answered Sep 19 '22 14:09

Ryan Cogswell