Home > Web Front-end > CSS Tutorial > Complete Guide to Creating a Sticky Navbar for Better Navigation in React JS

Complete Guide to Creating a Sticky Navbar for Better Navigation in React JS

Mary-Kate Olsen
Release: 2024-10-11 10:23:01
Original
872 people have browsed it

Panduan Lengkap Membuat Sticky Navbar untuk Navigasi Lebih Baik Pada React JS

In this session we will create a sticky navbar with Tailwind CSS and React JS.

You can see the installation process for React and Tailwind CSS in the previous article

Let's immediately create the code for the navbar

Create HTML for the Navbar display

<React.Fragment>
      <nav className={`fixed inset-x-0 top-0 z-50 flex items-center justify-center h-[60px] py-3 [&.is-sticky]:bg-white  border-b border-slate-200  [&.is-sticky]:shadow-lg [&.is-sticky]:shadow-slate-200/25 navba ${navClass}`} id="navbar">
        <div className="container 2xl:max-w-[90rem] px-4 mx-auto flex items-center self-center w-full">
          <div className="mx-auto">
            <ul id="navbar7" className={`absolute inset-x-0 z-20 items-center py-3 bg-white shadow-lg dark:bg-zink-600 dark:md:bg-transparent md:z-0 navbar-menu rounded-b-md md:shadow-none md:flex top-full ltr:ml-auto rtl:mr-auto md:relative md:bg-transparent md:rounded-none md:top-auto md:py-0`}>
              <li>
                <a href="#home"
                  className={`block md:inline-block px-4 md:px-3 py-2.5 md:py-0.5 text-15 font-medium text-slate-800 transition-all duration-300 ease-linear hover:text-red-500 [&.active]:text-red-500 dark:text-zink-100 dark:hover:text-red-500 dark:[&.active]:text-red-500 ${activeLink === "/Home" ? "active" : ""}`}
                  onClick={() => handleLinkClick("/Home")}
                >
                  Home</a>
              </li>
              <li>
                <a href="#features"
                  className={`block md:inline-block px-4 md:px-3 py-2.5 md:py-0.5 text-15 font-medium text-slate-800 transition-all duration-300 ease-linear hover:text-red-500 [&.active]:text-red-500 dark:text-zink-100 dark:hover:text-red-500 dark:[&.active]:text-red-500 ${activeLink === "/Features" ? "active" : ""}`}
                  onClick={() => handleLinkClick("/Features")}
                >
                  Layanan Kami</a>
              </li>
            </ul>
          </div>

        </div>
      </nav>
      <section className="relative mt-[60px] h-[800px] bg-yellow-600" id="home">
        <div className="flex items-center justify-center h-full">
          HOME
        </div>
        </section>
      <section className="relative h-[800px] bg-green-600" id="features">
        <div className="flex items-center justify-center h-full">
          FEATURES
        </div>
      </section>
    </React.Fragment>
Copy after login

Scroll Function

This function is used to change the status of the navbar to sticky, and also add smooth animations so that the page switching process is good


  const [navClass, setNavClass] = React.useState<string>('');

  const scrollNavigation = () => {
    var scrollUp = document.documentElement.scrollTop;
    if (scrollUp >= 50) {
      setNavClass('is-sticky');
    } else {
      setNavClass('');
    }
  };


  React.useEffect(() => {
    window.addEventListener('scroll', scrollNavigation, true);
    document.documentElement.classList.add("overflow-x-hidden", "scroll-smooth", "group");

    return () => {
      window.removeEventListener('scroll', scrollNavigation, true);
      document.documentElement.classList.remove("overflow-x-hidden", "scroll-smooth", "group");

    };
  }, []);

Copy after login

Set Active menu function

This function serves to change the active class in the menu, and directs the page according to the menu being accessed

  const [activeLink, setActiveLink] = React.useState<string>("/Home");
  const handleLinkClick = (target: string) => {
    setActiveLink(target);
  };

Copy after login

The complete script is as follows

import React from "react"

function App() {



  const [navClass, setNavClass] = React.useState<string>('');

  const scrollNavigation = () => {
    var scrollUp = document.documentElement.scrollTop;
    if (scrollUp >= 50) {
      setNavClass('is-sticky');
    } else {
      setNavClass('');
    }
  };


  React.useEffect(() => {
    window.addEventListener('scroll', scrollNavigation, true);
    document.documentElement.classList.add("overflow-x-hidden", "scroll-smooth", "group");

    return () => {
      window.removeEventListener('scroll', scrollNavigation, true);
      document.documentElement.classList.remove("overflow-x-hidden", "scroll-smooth", "group");

    };
  }, []);



  const [activeLink, setActiveLink] = React.useState<string>("/Home");
  const handleLinkClick = (target: string) => {
    setActiveLink(target);
  };



  return (
    <React.Fragment>
      <nav className={`fixed inset-x-0 top-0 z-50 flex items-center justify-center h-[60px] py-3 [&.is-sticky]:bg-white  border-b border-slate-200  [&.is-sticky]:shadow-lg [&.is-sticky]:shadow-slate-200/25 navba ${navClass}`} id="navbar">
        <div className="container 2xl:max-w-[90rem] px-4 mx-auto flex items-center self-center w-full">
          <div className="mx-auto">
            <ul id="navbar7" className={`absolute inset-x-0 z-20 items-center py-3 bg-white shadow-lg dark:bg-zink-600 dark:md:bg-transparent md:z-0 navbar-menu rounded-b-md md:shadow-none md:flex top-full ltr:ml-auto rtl:mr-auto md:relative md:bg-transparent md:rounded-none md:top-auto md:py-0`}>
              <li>
                <a href="#home"
                  className={`block md:inline-block px-4 md:px-3 py-2.5 md:py-0.5 text-15 font-medium text-slate-800 transition-all duration-300 ease-linear hover:text-red-500 [&.active]:text-red-500 dark:text-zink-100 dark:hover:text-red-500 dark:[&.active]:text-red-500 ${activeLink === "/Home" ? "active" : ""}`}
                  onClick={() => handleLinkClick("/Home")}
                >
                  Home</a>
              </li>
              <li>
                <a href="#features"
                  className={`block md:inline-block px-4 md:px-3 py-2.5 md:py-0.5 text-15 font-medium text-slate-800 transition-all duration-300 ease-linear hover:text-red-500 [&.active]:text-red-500 dark:text-zink-100 dark:hover:text-red-500 dark:[&.active]:text-red-500 ${activeLink === "/Features" ? "active" : ""}`}
                  onClick={() => handleLinkClick("/Features")}
                >
                  Layanan Kami</a>
              </li>
            </ul>
          </div>

        </div>
      </nav>
      <section className="relative mt-[60px] h-[800px] bg-yellow-600" id="home">
        <div className="flex items-center justify-center h-full">
          HOME
        </div>
        </section>
      <section className="relative h-[800px] bg-green-600" id="features">
        <div className="flex items-center justify-center h-full">
          FEATURES
        </div>
      </section>
    </React.Fragment>
  )
}

export default App

Copy after login

The above is the detailed content of Complete Guide to Creating a Sticky Navbar for Better Navigation in React JS. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template