Jasper
Jasper

Reputation: 2231

ternary operator inside map

I'm working on a webapp where the user views a list of items and can mark certain items as favourites. The favourites are provided as an array of ID's with a prop (this.props.favourites). To prevent duplicate entries I want to replace the 'add to favourites' button with a 'delete from favourites' button if the item.id is already in the this.props.favourites array.

However, the ternary If statement I've made crashes on a syntax error. Yet I thought I followed the official example (https://reactjs.org/docs/conditional-rendering.html) pretty closely.

This is the code that I used:

render() { 

       const items = this.state.items.map((item, index) => (
           <p key={index}>
               {item.name}
           </p>

           {(this.props.favourites.include(item) ? (
               <button>add fvourites</button>
             ) : (
               <button>delete</button>
     )}

       ));
       return (
           <div>
               <button onClick={this.LoadApi}>Show fetch Items</button>
               <div>{items}</div>
           </div>
       );
   }
}

Does anyone have an idea what I am doing wrong?

Upvotes: 8

Views: 21473

Answers (4)

TLadd
TLadd

Reputation: 6884

import * as React from 'react'

render() { 
  const items = this.state.items.map((item, index) => (
    <React.Fragment key={index}>
      <p>{item.name}</p>
      {this.props.favourites.includes(item) ? (
        <button>add favourites</button>
      ) : (
        <button>delete</button>
      )}
    </React.Fragment>
  ));

  return (
    <div>
      <button onClick={this.LoadApi}>Show fetch Items</button>
      <div>{items}</div>
    </div>
  );
}

Changes made:

  • remove extra parenthesis as Prakash sharma pointed out.
  • Wrap return value of map in React.Fragment. Cannot return multiple elements from a function without wrapping in a Fragment or array.
  • Change .include to .includes

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104489

Issues:

1- You are returning 2 elements inside map callback method, that is not correct, so wrap them inside a div.

2- You have a extra ( here: {(this.props.favourites.include(item)

3- Use includes not include.

Solution:

const items = this.state.items.map((item, index) => (
    <div key={index}>
        <p>
           {item.name}
        </p>

        {this.props.favourites.includes(item) ? (
           <button>add fvourites</button>
        ) : (
           <button>delete</button>
        )}
    </div>
))

Upvotes: 6

Leeroy_Wonkledge
Leeroy_Wonkledge

Reputation: 351

try something like below

{this.props.favourites.includes(item) ? <button>add favourites</button> :
     <button>delete</button>
 }

Upvotes: 3

Prakash Sharma
Prakash Sharma

Reputation: 16482

You have extra ( at the start. Change

{(this.props.favourites.include(item)...

to

{this.props.favourites.include(item)...

Upvotes: 2

Related Questions