If Else Inside Map Function

if else inside map function

Mistake in the tried solution

  1. data.attention is not an array.
  2. Check directly with value 1

Solution

  • Using Array.map to return a copy of jsx elements.
  • Using destructuring while looping through the array instead of writing item.attention
  • Checking the value so basically we can use ternary check (true ? 1: 0), since the value of attention is either 1 or 0 which represents true or false we can use it in this way.

Notes to improve

  • Instead of using wrapping with div you can use React fragments

const jsonData = {  "data": [{      "id": 1,      "attention": 1    },    {      "id": 2,      "attention": 1    },    {      "id": 3,      "attention": 0    }  ]}
const App = () => { return ( <div> { jsonData.data.map(({attention}) => { return ( <div> { attention ? <span>✅</span> : <span>❌</span> } </div> ) }) } </div> ) }
ReactDOM.render(<App /> , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script><div id='root'></div>

How to assign an IF statement inside a map function

ingredientIndex.forEach(currentIndex => {
^^^^^^^


Related Topics



Leave a reply



Submit