Home > Net >  How can I hide and show component on specific width in react js?
How can I hide and show component on specific width in react js?

Time:09-03

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;

CodePudding user response:

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;
  }
}

CodePudding user response:

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);
  }, []);
  • Related