1

There are quite a few questions and answers on this topic out there already, but I don't seem to get my JSX to render properly from a condtion within a map() function.

The function I am calling from my render() function looks like this:

renderAudiobookChoice(audioBookChoice) {
  if (audioBookChoice === "all") {
    return this.state.audiobooks.map(audiobook => (
      <AudiobookDetail key={audiobook.id} audiobook={audiobook} />
    ));
  }

  if (audioBookChoice === "poetry") {
    this.state.audiobooks.map(audiobook => {
      return audiobook.text_type === 2 ? (
        <AudiobookDetail key={audiobook.id} audiobook={audiobook} />
      ) : null;
    });
  }
}

So if my audioBookChoice = 'all', the AudiobookDetails are rendered properly. But if I audioBookChoice = 'poetry', it does not render anything to the screen anymore.

My linter gives me the follwoing warning: "Expected to return a value at the end of arrow function. (array-callback-return)". This is confusing me, as I am under the impression that I should be returning something following my terniary operator.

Any help would be much appreciated.

Tholle
  • 108,070
  • 19
  • 198
  • 189
  • Possible duplicate of [map doesn't return anything](https://stackoverflow.com/questions/45670326/es6-array-map-doesnt-return-anything-reactjs) – Mayank Shukla Jul 10 '18 at 13:08

4 Answers4

3

You're missing the the return in the poetry section:

if (audioBookChoice === 'poetry') {
    return (
      this.state.audiobooks.map(audiobook => {
        return audiobook.text_type === 2 ?
            <AudiobookDetail 
                key={audiobook.id} audiobook={audiobook} 
            />

        : 
            null;
        });
    }
  );
}
Ted
  • 14,757
  • 2
  • 41
  • 58
2

You are not returning the result inside of your second if statement.

if (audioBookChoice === "poetry") {
  return this.state.audiobooks.map(audiobook => {
    return audiobook.text_type === 2 ? (
      <AudiobookDetail key={audiobook.id} audiobook={audiobook} />
    ) : null;
  });
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
2

Because you're not returning the map of the array anymore.

use this:

if (audioBookChoice === "poetry") {
  return this.state.audiobooks.map(audiobook => {
    return audiobook.text_type === 2 ? (
      <AudiobookDetail key={audiobook.id} audiobook={audiobook} />
    ) : null;
  });
}
user229044
  • 232,980
  • 40
  • 330
  • 338
Jorgedl
  • 137
  • 3
2

You are missing return statement,change to

 if (audioBookChoice === "poetry") {
    return this.state.audiobooks.map(audiobook => {
      return audiobook.text_type === 2 ? (
        <AudiobookDetail key={audiobook.id} audiobook={audiobook} />
      ) : null;
    });
  }
}
Israel.z
  • 321
  • 2
  • 6