0

I want to toggle my button it works but the problem is I want to create a more responsive. when the device width is 440 px my sidebar will be closed. When we click the button that time it will show. how can I do it?

But here my method not working.

import React, { useState } from "react";
import SideBar from "./components/SideBar";
import "./App.css";

function App() {
  const [sidebar, setSidebar] = useState(false);

  const sideBarShowHide = (e) => {
    e.preventDefault();
    setSidebar(!sidebar);
  };

  if (window.matchMedia("max-width:440px").matches) {
    setSidebar(!sidebar);
  }

  return (
    <div className="App">
        {sidebar || <SideBar />}
        <button onClick={sideBarShowHide}>Hide/show</button>
    </div>
  );
}

export default App;
Omor Faruk
  • 57
  • 8

2 Answers2

0

I would use a media query to set the CSS display property to none when width 400px is reached.

 return (
    <div className="App">
      <div classname="sidebar">
       <SideBar />
      </div>
      <button onClick={sideBarShowHide}>Hide/show</button>
    </div>
  );

Set the display to none when max width is 400px


@media only screen and (max-width: 400px) {
  .sidebar {
   display: none;
  }
}

msmoore
  • 396
  • 2
  • 12
0

My sugestion is create an event Listener and a function that sets the state.

  const toggleSidebar = () => {
    setSidebar(!sidebar);
  };

  useEffect(() => {
    const matchMedia = window.matchMedia("(max-width:440px)");
    matchMedia.addEventListener(toggleSidebar);
    return () => matchMedia.removeEventListener(toggleSidebar);
  }, []);
lkminzoni
  • 49
  • 4
  • It's can acceptable proposal but is there any appreciate or better way? – Omor Faruk Sep 02 '22 at 22:26
  • What you mean by better way? a shorter way? an usual way? I believe there is no standart or better way to solve this issue, I usually tend to use more Javascript in my projects so for me this is a ok solution lol. – lkminzoni Sep 02 '22 at 23:51
  • Your method not working I try a lot of ways. But can't control it without CSS. If you have better options please suggest me. I will be benefited if is possible. @lkminzoin – Omor Faruk Sep 13 '22 at 19:00