简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM