Home > Net >  how to display items with category name as title
how to display items with category name as title

Time:12-03

hi I have multiple items with different categories. I want to display all item with its Category name as a title at header. My code displaying each item but category Title repeats with each item. I want Category title only one time at the top and then its items list. MY Code is this

{                               
  formsList.map((item, index,temp=0) => {
    if(temp!==item.cat_id)
    {
      temp = item?.cat_id;                            
      return (
        <div className="custom-control custom-radio mb-3">
         <div className="form-control-label"> {item.category_title}</div>
          <input
            className="custom-control-input"
            id= {item.id}
            name= {item.cat_id}
            type="radio"
          />
          <label className="custom-control-label" htmlFor={item.id}>
            {item.form_title} {temp}
          </label>
        </div>
       )
    }

    return (
      <div className="custom-control custom-radio mb-3">
        <input
          className="custom-control-input"
          id= {item.id}
          name= {item.cat_id}
          type="radio"
        />
        <label className="custom-control-label" htmlFor={item.id}>
        {item.form_title}
        </label>
      </div>
     )
  })
}

CodePudding user response:

One way to solve this problem is to store the previous category ID in a variable, and only render the category title when the current category ID is different from the previous one. Here is an example of how you can do this:

{
  let prevCatId = null;

  formsList.map((item, index) => {
    if (prevCatId !== item.cat_id) {
      prevCatId = item.cat_id;

      return (
        <div className="form-control-label">{item.category_title}</div>
      );
    }

    return (
      <div className="custom-control custom-radio mb-3">
        <input
          className="custom-control-input"
          id={item.id}
          name={item.cat_id}
          type="radio"
        />
        <label className="custom-control-label" htmlFor={item.id}>
          {item.form_title}
        </label>
      </div>
    );
  });
}

CodePudding user response:

Please try this

json part

const recipes = [{
    id: 716429,
    title: "Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs",
    image: "http://ovuets.com/uploads/716429-312x231.jpg>",
    dishTypes: [
        "lunch",
        "main course",
        "main dish",
        "dinner"
    ],
    recipe: {
    // recipe data
    }
}]

function part

export default function Recipes() {
return (
<div>
    {recipes.map((recipe) => {
    return <div key={recipe.id}>
        <h1>{recipe.title}</h1>
        <img src={recipe.image} alt="recipe image" />
        {recipe.dishTypes.map((type, index) => {
            return <span key={index}>{type}</span>
        })}
    </div>
    })}
</div>
)}
  • Related