react sidebar component in javascript

To create a Sidebar component in React, you can follow these simple steps:

  1. Create a new file named Sidebar.js and import React, useState and CSS for styling:
index.tsx
import React, { useState } from "react";
import "./Sidebar.css";
65 chars
3 lines
  1. Create a functional component named Sidebar and define its state using the useState hook:
index.tsx
function Sidebar() {
  const [isOpen, setIsOpen] = useState(false);
  // ...
77 chars
4 lines
  1. Render the sidebar component with JSX and use CSS classes to toggle the open or closed state based on the isOpen value:
index.tsx
return (
    <div className={isOpen ? "sidebar-container open" : "sidebar-container"}>
      <button onClick={() => setIsOpen(!isOpen)}>toggle</button>
      <div className="sidebar-content">
        <h2>Sidebar</h2>
        <p>Content goes here...</p>
      </div>
    </div>
);
280 chars
10 lines
  1. Add CSS to the Sidebar.css file to style the sidebar (use the .open class to adjust styles when the sidebar is open):
.sidebar-container {
  width: 0;
  height: 100%;
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  background-color: #111;
  transition: width 0.5s;
}

.sidebar-container.open {
  width: 250px;
}

.sidebar-content {
  padding: 16px;
  color: #fff;
}
258 chars
20 lines
  1. Finally, import the Sidebar component in your main App.js file and render it:
index.tsx
import React from "react";
import Sidebar from "./Sidebar";

function App() {
  return (
    <div>
      <Sidebar />
      <h1>Main Content</h1>
    </div>
  );
}

export default App;
184 chars
14 lines

gistlibby LogSnag