Reputation: 139
So I have this problem where I want to exclude a component in react. I already put the component that I want to exclude but it is still displaying.
Here is my code:
App.js
return (
<Router>
<div className="App">
<div className="wrapper">
<Navbar />
<Sidebar />
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/note" element={<Notelist />} />
<Route path="/note/create" element={<Create />} />
<Route path="/note/:id" element={<Notedetails />} />
</Routes>
</div>
<Routes>
<Route path='*' element={<NotFound />}></Route>
</Routes>
</div>
</Router>
);
}
export default App;
NotFound.js
const NotFound = () => {
return (
<div className="page-wrap d-flex flex-row align-items-center">
<div className="container">
<div className="row justify-content-center">
<div className="col-md-12 text-center">
<span className="display-1 d-block">404</span>
<div className="mb-4 lead">The page you are looking for was not found.</div>
<Link to='/'>Back to Home</Link>
</div>
</div>
</div>
</div>
);
}
export default NotFound;
Now when I type anything in the URL this will be displayed:
but this is not what I want. Sidebar and Nav bar should not be visible. It should be like this:
I'm just new to reactjs so bear with me.
Upvotes: 1
Views: 830
Reputation: 1185
If you want the <Sidebar />
to be rendered conditionally like in some pages it should be visible and other pages not. Then in that case you can adopt:
<SideBar/>
into main application file i.e App.js. Keep this at page level.<SideBar/>
component conditional like put a regex for path match and then render your component [which is not a good practice]<Switch/>
, <BrowserRouter/>
, <Route/>
then check the below implementation:note : you need to place 404 route before main app route to match first.
const Main = () => (
<BrowserRouter>
<Switch>
<Route path="/404" exact render={() => <div>404</div>} />
<Route path="/" component={App} />
</Switch>
</BrowserRouter>
);
For App.js/index.js
import React from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Navbar />
<Sidebar />
<Switch>
<Route exact path="/" element={<Home />} />
<Route path="/note" element={<Notelist />} />
<Redirect to="/404" />
</Switch>
</div>
);
Upvotes: 1