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


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;
560 views

2 Answers

0
John Szymanski John Szymanski

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;
  }
}
0
Taylor Hawkes Taylor Hawkes

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

It's can acceptable proposal but is there any appreciate or better way?

- Nick Talman Sep 03, 2022 13:25

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.

- Taylor Hawkes Sep 03, 2022 13:36

Your Answer

Signin to post your answer