ternary operator inside map

那年仲夏 提交于 2019-12-06 10:03:29

try something like below

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

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>
))

You have extra ( at the start. Change

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

to

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!