majid beg
majid beg

Reputation: 196

How to hide the sidebar from perticular page in react.js?

I am implementing the global navigation sidebar (left collapsible) with react but I want to exclude or hide my sidebar from some routes or components.

and when I importing it to a particular component I am loosing my component responsiveness.

import React from "react";
//more imports are here

const App = () => (
  <ThemeProvider theme={theme}>
    <div>
      <AppToolbar />
      <div className="myclass">
        <SideBar>
          <Route path="/" exact component={Home} />
          <Route path="/setting" component={Setting} />
          <Route path="/help" component={Help} />
          <Route path="/about" component={About} />
        </SideBar>
      </div>
    </div>
  </ThemeProvider>
);

export default App;

Looking for the solution to hide the sidebar from Route path="/" exact component={Home} /> route. or is there any other way to achieve the same functionality.

Upvotes: 4

Views: 4032

Answers (1)

Kevin Moe Myint Myat
Kevin Moe Myint Myat

Reputation: 2185

Looks like the routes need to be taken out from the SideBar JSX first so that routes won't be wrapped inside SideBar indefinitely.

Pass a function props to the route components which can change the state of parent component's sidebar. Then at the route where you want to hide sidebar, call that function which will take the SideBar JSX out from the DOM.

Example:

import React from "react";
//more imports are here

const App = () => {
const [showSidebar,setShowSidebar] = React.useState();

const handleToggleSideBar = () => {
//togglesidebar with useState
setShowSidebar(!showSidebar);
}

 return (
  <ThemeProvider theme={theme}>
    <div>
      <AppToolbar />
      <div className="myclass">
        {showSidebar &&  <SideBar />}
          <Route path="/" exact render={(props) => <Home  toggleSideBar={handleToggleSideBar } {...props} />} />
          <Route path="/setting" render={//do the same thing like Home} />
      </div>
    </div>
  </ThemeProvider>
)};

export default App;

Home.jsx

    export const Home = ({toggleSideBar}) => {
    useEffect(() => {
      toggleSideBar();
      },[]);
    }

Upvotes: 1

Related Questions