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 "}"

vsync
  • 118,978
  • 58
  • 307
  • 400
  • 1
    Of course, I always research before asking thanks, also this isn't a duplicate... –  Nov 04 '19 at 20:12
  • `{[, ].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) – Patrick Roberts Nov 04 '19 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 –  Nov 04 '19 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 `
    ` or w/e.
    – wdm Nov 04 '19 at 20:16
  • it is a duplicate of: https://stackoverflow.com/q/44649698/104380 – vsync Nov 04 '19 at 20:16
  • @vsync I would say this is different (but maybe seen as splitting hairs), since this is asking how to inline conditionally render multiple elements, while the linked duplicates don't suggest a way (but do suggest a way via an `if/else` statement and a ternary operator. – Ehtesh Choudhury Mar 02 '20 at 23:43

1 Answers1

20

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} />
 </>
}
vsync
  • 118,978
  • 58
  • 307
  • 400
  • Yeah I already had everything in a fragment container, wasn't aware that I had to include another one for a conditional. Noted –  Nov 04 '19 at 20:20
  • @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 Nov 04 '19 at 20:22
  • 1
    @vsync RE: `Stackoverflow doesn't allow updating the linked to a duplicate once it has been set` [_yes it does_](https://i.stack.imgur.com/WYzxG.png) – Patrick Roberts Nov 04 '19 at 20:30
  • That's not new, [it's been around long before the recent design changes](https://meta.stackexchange.com/q/291824/313880). – Patrick Roberts Nov 04 '19 at 20:34