skip to Main Content

so basically sidebar and navbar is both different components in my code i have navbar.jsx and sidebar.jsx and both are being called under student.jsx … now on mobile screens i want that the sidebar also gets into that hamburger icon in the navbar when on mobile screens and that user can navigate different pages such as dashboard counselling etc when clicked on the icon which contains the sidebar and its different pages

i tried to hide the sidebar in mobile screen my putting the css display none in mobile screens and tried using usestate hook and toggle logic but i cant put the sidebar in the navbar and i want them to be different just in mobile screens they should be together this is what its looking like right now

2

Answers


  1. Assuming you write plain react with no 3rd party libraries, you can achieve this by using media queries in the CSS.

    In the sidebars.jsx at the root element, add a className such as sidebar, and for the navbar.js at the root element, add a className such as navbar.

    Then you can create a CSS files that will contain the following:

    @media (width <= 840px) {
      .sidebar {
        display: none;
      }
    
      .navbar {
        display: block;
      }
    }
    
    @media (width > 840px) {
      .sidebar {
        display: block;
      }
    
      .navbar {
        display: none;
      }
    }
    
    Login or Signup to reply.
  2. The solution to that is to use window.innerWidth and ternary operators

    to use a ternary operator:

    {condition ? <elementToRenderIfTrue> : <elementToRenderIfFalse>}
    

    in the code of your navbar function

    {window.innerWidth < 800 ? <button>Hamburger Bar</button> : null}
    

    and in your page

    {window.innerWidth > 800 ? <sideBar /> : null}
    

    also you can change the width with any width mobile users usually have

    no CSS needed

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search