10

I have a slider and I want to only show the arrows if the slider has more than one image.

I've tried something like the following in the return

{(this.state.images > 1)
  <LeftArrow goToPrevSlide={this.goToPrevSlide} />
  <RightArrow goToNextSlide={this.goToNextSlide} />
}

and I get the following Parsing error: Unexpected token, expected "}"

6
  • 1
    Of course, I always research before asking thanks, also this isn't a duplicate... Commented Nov 4, 2019 at 20:12
  • {[<LeftArrow key="left" goToPrevSlide={this.goToPrevSlide} />, <RightArrow key="right" goToNextSlide={this.goToNextSlide} />].filter(() => this.state.images > 1)} could work in this case, though a bit ugly looking (and renders the arrows even when they're not used) Commented Nov 4, 2019 at 20:12
  • Thanks, @PatrickRoberts that works, can you explain what's going on in the code so I can understand it? Looks like a filter array Commented Nov 4, 2019 at 20:14
  • 1
    {this.state.images > 1 && ...} You'll also need to wrap your two child components with a single parent. You can use a Fragment <>...</> or a <div> or w/e. Commented Nov 4, 2019 at 20:16
  • it is a duplicate of: stackoverflow.com/q/44649698/104380 Commented Nov 4, 2019 at 20:16

1 Answer 1

22

You must wrap both your elements in some container. This container is treated as a "whole", no matter what is inside it. In this example below I am using an empty Fragment container

Also, notice that only the piece of code written directly after the && is executed if the first part, before the && was resolved as true. (Read more about &&).

This is why you must wrap everything which should be conditionally-rendered in a container, because if you didn't, only the first element would have been conditionally rendered and anything after it would always get rendered

{ this.state.images > 1 && <>
  <LeftArrow goToPrevSlide={this.goToPrevSlide} />
  <RightArrow goToNextSlide={this.goToNextSlide} />
 </>
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yeah I already had everything in a fragment container, wasn't aware that I had to include another one for a conditional. Noted
@nightcode - You did not use the javascript && sign to signal what comes after it should run only if the first part of the statement is true
@vsync RE: Stackoverflow doesn't allow updating the linked to a duplicate once it has been set yes it does