Home > database >  Add routing to navbar (react & tailwind)
Add routing to navbar (react & tailwind)

Time:08-31

import { useState } from "react";
const App = () => {
  const [open, setOpen] = useState(true);
  const Menus = [
    { title: "Home", src: "0" },
    { title: "Site1", src: "1", gap: true },
    { title: "Site2 ", src: "2" },
    { title: "Site3", src: "3" },
    { title: "Site4", src: "4" }
  ];

  return (
    <div className="flex">
      <div
        className={` ${
          open ? "w-72" : "w-20 "
        } bg-gray-800 p-5  pt-8 sticky top-0 left-0 h-[930px] duration-300`}
      >
        <img
          src="./src/assets/control.png"
          className={`absolute cursor-pointer -right-3 top-9 w-7 border-dark-purple
           border-2 rounded-full  ${!open && "rotate-180"}`}
          onClick={() => setOpen(!open)}
        />
        <div className="flex gap-x-4 items-center">
          <img
            src="./src/assets/logo.png"
            className={`cursor-pointer duration-500 ${
              open && "rotate-[360deg]"
            }`}
          />
          <h1
            className={`text-white origin-left font-medium text-xl duration-200 ${
              !open && "scale-0"
            }`}
          >
            Site
          </h1>
        </div>
        <ul className="pt-6">
          {Menus.map((Menu, index) => (
            <li
              key={index}
              className={`flex  rounded-MD p-2 cursor-pointer hover:bg-light-white text-gray-300 text-sm items-center gap-x-4 
              ${Menu.gap ? "mt-9" : "mt-2"} ${
                index === 0 && "bg-light-white"
              } `}
            >
              <img src={`./src/assets/${Menu.src}.png`} />
              <span className={`${!open && "hidden"} origin-left duration-200`}>
                {Menu.title}
              </span>
            </li>
          ))}
        </ul>
      </div>

This is the code that I got after following this tutorial: Tutorial

How can I link my other pages with the navbar? So clicking for example Site1 will direct the user to Site1?

The problem is that I can't use tags or hfref in this case and I have no idea how to solve my problem as I'm just learning react.

CodePudding user response:

Have a look and read into the React-router: https://reactrouter.com/en/main/getting-started/tutorial

To create a link use the tag instead of the tag

CodePudding user response:

Multiple things you can do here. If you want to stick with clickable buttons, you could use React Router and the, for each Menu add an onClick={() => router.push(Menu.title)} (subject to whatever your actual url is).

Otherwise, in a more native way, you could use a tags instead of span tags, which can receive href={Menu.title}. The downside here is that you'd have to style them again, as a tags have browser-specific default styles.

  • Related