LiquidDeath
LiquidDeath

Reputation: 1828

How to conditional render inside map in a functional component of react js

I have an array. in which i want to iterate over and do conditional checks and display the correct element. i'm using functional component.

Below is an example :

import React, { useState, useEffect } from "react";

function Job(props) {
  const [resp_data, setdata] = useState("");
  const [look, setlook] = useState("");
  useEffect(() => {
//    some api calls happen here and response data is stored in state resp_data
  }, [props]);
  return (
    <>
    <div className="product_list">
        {resp_data.length > 0
          ? resp_data.map((item) => {
              {item.looking_for === "work" ? (
                  <div className="card-rows work" key={item.id}>
                    work
                  </div>
                ) : (<div className="card-rows no_work" key={item.id}>
                No work
              </div>)
              }
            })
          : <div>array length is 0</div>}
      </div>
    </>
  );
}

export default Job;

The response data received from api call happening inside useEffect is stored in state variable resp_data.

if resp_data length is not zero, i need to iterate over the list and check if the field value "looking_for" is equal to "work"

if true display a component , else display another component.

if resp_data length is zero display "array length is zero"

this i want to implement, but i could not find many answers for functional components. i have tried many possible ways by switching, changing the braces etc..my hard luck.

Any help is greatly appreciated.

Upvotes: 0

Views: 5563

Answers (1)

yondu_udanta
yondu_udanta

Reputation: 807

You are not returning anything from the 'map' function.

resp_data.map((item) => (
          item.looking_for === "work" ? (
              <div className="card-rows work" key={item.id}>
                work
              </div>
            ) : (<div className="card-rows no_work" key={item.id}>
            No work
          </div>)
          )
        )

Upvotes: 5

Related Questions