Create a Sliding Navbar in Reactjs

·

2 min read

To design a sliding navbar in React.js, we will first have to create a basic navbar component. We can do this by creating a functional component that returns a navbar inside a container div. We can then apply CSS styles to create a sliding animation.

Here's an example code for the sliding navbar:

import { useState } from 'react';

function SlidingNavbar() {
  const [isOpen, setIsOpen] = useState(false);

  const toggleNavbar = () => {
    setIsOpen((prevState) => !prevState);
  };

  return (
    <div className="navbar-container">
      <button className="navbar-toggle" onClick={toggleNavbar}>
        <div className="navbar-toggle--icon" />
      </button>
      <nav className={`navbar ${isOpen ? 'opened' : 'closed'}`}>
        <ul>
          <li><a href="#">Home</a></li>
          <li><a href="#">About</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </nav>
    </div>
  );
}

export default SlidingNavbar;

Here, we have used React hooks to create a state for the navbar that checks whether it is open or not. Inside our SlidingNavbar component, we have created a button that toggles the navbar state by calling the toggleNavbar function, which changes the state of the navbar between open and closed. We have also applied CSS classes based on the state to create an animation effect.

Here's an example of CSS style we can apply to create the sliding effect:

.navbar {
  background-color: #333;
  position: absolute;
  top: 60px;
  right: 0;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  transition: transform 0.3s ease-in-out;
  transform: translateX(100%);
}

.navbar.opened {
  transform: translateX(0);
}

.navbar ul {
  padding: 0;
  list-style-type: none;
  text-align: center;
}

.navbar li {
  margin: 15px 0;
}

.navbar a {
  color: #fff;
  text-decoration: none;
  font-size: 1.5rem;
}

In the CSS above, we have applied styles to the navbar container, navbar, and navbar links. With the translateX() function, we have applied a sliding animation when the navbar is opened or closed.

We can now use the SlidingNavbar component in our app and customize it as per our requirement.