Home > OS >  React does not render NavLink but prints items in console
React does not render NavLink but prints items in console

Time:01-21

Whole App is wrapped inside BrowserRouter and my Navlink is inside of Sidebar. I want to render them dynamically meaning, but for some reason NavLink's are not rendered. I have tried printing them in console just to see if my code is getting reached and it does but doesn't render.

EDIT: I have tried rendering other tags and none of them are rendering. Only console.log is working.

 const Sidebar = ({ user, closeToggle }) => {
  const categories = [
    { name: "Animals" },
    { name: "wallpapers" },
    { name: "Photography" },
    { name: "Gaming" },
    { name: "Coding" },
  ];
  return (
    <div className="flex flex-col justify-between bg-white h-full overflow-y-scrikk min-w-210 hide-scrollbar">
      <div className="flex flex-col">
      
        <div className="flex flex-col gap-5">
         
          <h3 className="capitalize mt-2 px-5 text-base 2xl:text-xl">
            discover categories
          </h3>
          {categories &&
            categories.slice(0, categories.length - 1).map((item,id) => {
              console.log(item.name);
              <NavLink
                to={`/category/${item.name}`}
                className={({ isActive }) =>
                  isActive ? isActiveStyle : isNotActiveStyle
                }
                onClick={handleCloseSidebar}
                key={id}
              >
                console.log(item.name);
                <h3>{item.name}</h3>
              
              </NavLink>;
            })}
        </div>
      </div>
    </div>
  );
};

CodePudding user response:

You need to return JSX from the mapping callback if you are using an arrow function with a function body, i.e. () => { ...; return ...; }.

{categories &&
  categories.slice(0, categories.length - 1).map((item, id) => {
    console.log(item.name);
    return (
      <NavLink
        to={`/category/${item.name}`}
        className={({ isActive }) =>
          isActive ? isActiveStyle : isNotActiveStyle
        }
        onClick={handleCloseSidebar}
        key={id}
      >
        <h3>{item.name}</h3>
      </NavLink>
    );
  })
}

Arrow functions without a body have an implicit return.

{categories &&
  categories.slice(0, categories.length - 1).map((item, id) => (
    <NavLink
      to={`/category/${item.name}`}
      className={({ isActive }) =>
        isActive ? isActiveStyle : isNotActiveStyle
      }
      onClick={handleCloseSidebar}
      key={id}
    >
      <h3>{item.name}</h3>
    </NavLink>
  ))
}
  • Related