Home > database >  Reactjs getting multiple items when clicking only on single items
Reactjs getting multiple items when clicking only on single items

Time:09-28

How I can get only single sub-category ? right now I am clicking on single category but getting result for all related sub category. See the screenshot. Electronic have two subcategory mobile and gadget but when clicking only on mobile I am also getting gadget. enter image description here

here is code:

const PostSingleAd = ({ data, itemOpenedId, setItemOpenedId,setText }) => {
  const [showsubcat, setShowSubCat] = useState(false);

  let subcategory = () => {
    setShowSubCat((prev) => !prev);
    setItemOpenedId(data.id);
    setText(data.main_category)
  };
   let subclick = (e)=>(
       
       console.log(e.currentTarget.textContent)
  )
  useEffect(() => {
    if (itemOpenedId !== data.id) {
      setShowSubCat(false);
    }
  }, [itemOpenedId]);



 return (
    <>
      <li  id="category" onClick={subcategory}>
        {data.main_category}
      </li>
      {showsubcat && (
        <li onClick={subclick}>
           {data.sub_cat_bp.map((data)=>(<>
          <i  id="sub_category"></i>{" "}
          {data.sub_category}
          </>) 
        </li>
      )}
    </>
  );
};


const PostAds = () => {
  const [itemOpenedId, setItemOpenedId] = useState();
  const[text,setText] = useState();
  console.log(text)
  return data.map((data) => (
    <PostSingleAd
      data={data}
      itemOpenedId={itemOpenedId}
      setItemOpenedId={setItemOpenedId}
      setText={setText}

    />
  ));
};

When I will click on mobile I should get text only for mobile not mobile and gadget both. here is my api data look like:

[
  {
    "main_category": "Electronic",
    "sub_cat_bp": [
      {
        "sub_category": "Mobile",
        "id": 1
      },
      {
        "sub_category": "Gadget",
        "id": 2
      }
    ]
  },
  {
    "main_category": "Car",
    "sub_cat_bp": [
      {
        "sub_category": "Car glass",
        "id": 3
      },
      {
        "sub_category": "Dorr brll",
        "id": 4
      }
    ]
  }
]

CodePudding user response:

Your li element should be inside map callback

  return (
    <>
      <li  id="category" onClick={subcategory}>
        {data.main_category}
      </li>
      {showsubcat &&
        data.sub_cat_bp.map((data) => (
          <li onClick={subclick}> // <-- moved inside map
            <i  id="sub_category"></i>{" "}
            {data.sub_category}
          </li>
        ))}
    </>
  );

CodePudding user response:

your <li> should be inside map and you also need to assign a unique key to <li>

  • Related