Why is my React Router selecting two Routes in a nested Switch? - javascript

My App.js is as such:
const App = () => {
return (
<div className="App">
<Router>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/studio">
<Studio />
</Route>
<Route path="*" component={NotFound} />
</Switch>
</Router>
</div>
)
}
& my Studio.js is as follows:
const Studio = () => {
let { path } = useRouteMatch()
return (
<>
<Switch>
<Route exact path={path}>
<Editor />
</Route>
<Route path={`${path}/categories`}>Studio/Categories</Route>
<Route component={NotFound} />
{/* <Route exact path={`${path}/*`} component={NotFound} /> */}
</Switch>
</>
)
}
It seems routing is working perfectly fine for App.js but for Studio.js, the Switch doesn't stop at the first match and is rendering <NotFound/> when visiting /studio as well as /studio/categories.
What can I do to make it work such that only one Route is rendered within the Switch which is the default behaviour as per the docs if I'm not wrong?
Reproducible SandBox: https://codesandbox.io/s/react-router-nested-glled

You have import typo BrowserRouter as Switch, you just need to import regular Switch in Nested component
import {
BrowserRouter as Switch, // remove `BrowserRouter as` thing
Route,
useRouteMatch
} from "react-router-dom";

Related

display component across all paths except some in react-router-dom v6

I'm attempting to create a few routes on my web app using react-router. However, some pages need to share components - such as the Navigation or Footer - where others do not.
What I essentially need is a way to check if a path doesn't match a few preset locations, and if it doesn't then render the content.
At the moment I'm doing this like so:
const displayComponentIfAllowed = (location, component) => {
const C = component;
const globalComponentsDisallowedPaths = ["/booking"];
// If the path matches something within the blocked list, then return null.
let allowToRender = true;
globalComponentsDisallowedPaths.forEach(disallowedPath => {
if(location.pathname === disallowedPath){
allowToRender = false;
}
});
// Otherwise, return component to render.
return allowToRender ? <C /> : null;
}
return (
<Router>
<Routes>
<Route render={({ location }) => displayComponentIfAllowed(location, Navigation)} />
<Route path="/">
<Route index element={<Home />} />
<Route path="booking/:customer_id" element={<Booking />} />
</Route>
<Route render={({ location }) => displayComponentIfAllowed(location, Footer)} />
</Routes>
</Router>
);
However, ever since V6 of react-router-dom has been introduced, this doesn't seem to work. I imagine this is because the render prop has been deprecated (although I'm unsure, but there's no mention of it in the docs).
Are there any workarounds - or a better implementation of this which works with V6? Cheers
Create a layout component that renders the UI components you want and an Outlet for nested routes to be rendered into.
Example:
import { Outlet } from 'react-router-dom';
const HeaderFooterLayout = () => (
<>
<Navigation />
<Outlet />
<Footer />
</>
);
...
import {
BrowserRouter as Router,
Routes,
Route
} from "react-router-dom";
...
<Router>
<Routes>
<Route element={<HeaderFooterLayout />} >
<Route path="/">
<Route index element={<Home />} />
... other routes you want to render with header/footer ...
</Route>
</Route>
<Route path="booking/:customer_id" element={<Booking />} />
... other routes you want to not render with header/footer ...
</Routes>
</Router>

Why my components don't display on my React page?

So I'm learning React and building an app with multiple pages, I made a Routes file which looks like this:
import 'swiper/swiper.min.css';
import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "../pages/Home";
import Catalog from "../pages/Catalog";
import Detail from "../pages/Detail";
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
component={Catalog}
/>
<Route
path='/:category/:id'
component={Detail}
/>
<Route
path='/:category'
component={Catalog}
/>
<Route
path='/'
exact
component={Home}
/>
</Routes>
);
}
And App.js looks like this:
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Header from './components/header/Header';
import Footer from './components/footer/Footer';
import Router from './config/Router';
function App() {
return (
<BrowserRouter>
<Routes>
<Route render={props =>{
<>
<Header {...props}/>
<Router/>
<Footer/>
</>
}}/>
</Routes>
</BrowserRouter>
);
}
export default App;
As you see, I have a browser router and Route which passes props to a component(as I understood) but for some reason the components don't display on the page(original components just have with their name inside of them, but they don't display in App.js).
And my console also says:
No routes matched location "/"
In routes.jsx file. I'm guessing it should lead to main page, but for some reason the route doesn't match and components in App.js don't display.
In Version 6.0.0 there is not any component prop in Route. It has been changed to element. So you need to change your Router to :
const Router = () => {
return (
<Routes>
<Route
path='/:category/search/:keyword'
element={Catalog}
/>
<Route
path='/:category/:id'
element={Detail}
/>
<Route
path='/:category'
element={Catalog}
/>
<Route
path='/'
exact
element={Home}
/>
</Routes>
);
}
As you've said you're using react-router-dom 6.0.2, and it seems that the tutorial you are following is for the older version (5?). There were some breaking changes in version 6.
You need to change your Router component to use element instead of component:
const Router = () => {
return (
<Routes>
<Route path="/:category/search/:keyword" element={<Catalog />} />
<Route path="/:category/:id" element={<Detail />} />
<Route path="/:category" element={<Catalog />} />
<Route path="/" exact element={<Home />} />
</Routes>
);
};
and also your App component seems to be getting in the way with the nested route.
I think it can be simplified to:
function App() {
return (
<BrowserRouter>
<>
<Header />
<Router />
<Footer />
</>
</BrowserRouter>
);
}
You can see a working demo on stackblitz

Programmatically navigate while using HashRouter

I'm using HashRouter for my routes in a react.js app. I then have a function which does the following:
this.props.history.push('/somePath');
The problem is, ever since I started using HashRouter, the page doesn't push to that path when that function gets called.
I logged this.props.history, and push was there.
How can I programmatically navigate while using HashRouter?
Note: I used withRouter
Here's the code:
import React, { Component } from 'react';
import { HashRouter, Route, Switch, Redirect, withRouter } from 'react-router-dom';
// Other imports
class App extends Component {
navigate = () => {
this.props.history.push('/route1');
console.log(this.props.history);
};
render() {
return (
<div className="App">
<Header />
<HashRouter>
<Switch>
<Route
path="/route1"
exact
render={() => (
<FirstRoute someSetting='setting1'/>
)}
/>
<Route
path="/route2"
exact
render={() => (
<SecondRoute anotherSetting='Really Cool'/>
)}
/>
<Route path="/404" component={NotFound} />
<Route exact path="/" render={() => <HomePage someSettings='Home Page' />} />
<Redirect to="/404" />
</Switch>
</HashRouter>
<BottomBar />
</div>
);
}
}
export default withRouter(App);

How to skip header and footer for certain routes in ReactJS?

I have the following code which renders an app with a header and footer for all pages.
app.js
import React from 'react';
import {
Route,
Switch
} from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'
import Layout from './components/Layout'
import Home from './homeComponent';
import Login from './loginComponent';
import Dashboard from './dashboardComponent';
const App = ({ history }) => {
return (
<Layout>
<ConnectedRouter history={history}>
<Switch>
<Route exact={true} path="/" component={Home} />
<Route path="/login" component={Login} />
<Route path="/dashboard" component={Dashboard} />
... more routes
<Route component={NoMatch} />
</Switch>
</ConnectedRouter>
</Layout>
);
};
export default App;
layout.js
import Header from './headerComponent'
import Footer from './footerComponent'
import React, {Component} from 'react'
class Layout extends Component {
render() {
return (
<div>
<Header />
{this.props.children}
<Footer />
</div>
)
}
}
What is the best way to skip rendering of the header and footer for certain pages like Home and Login routes?
I'd recommend creating two layouts with their own header and footers and a private route:
Public Layout
export const PublicLayout = (props) => <div>
<PublicHeader/>
<Switch>
<Route exact path="/" component={HomePage}/>
<Route exact path='/signin' component={SigninForm} />
<Route exact path='/signup' component={Signup} />
</Switch>
<PublicFooter/>
Protected Layout
export const ProtectedLayout = (props) => <div>
<ProtectedHeader/>
<Switch>
<PrivateRoute exact path='/app/dashboard' component={Dashboard} />
<Route component={NotFound} />
</Switch>
<ProtectedFooter/>
Define high-level routes in app.js:
export default () => {
return <div>
<Switch>
<Route path='/app' component={ProtectedLayout} />
<Route path='/' component={PublicLayout} />
</Switch>
</div>
}
Define PrivateRoute:
export default ({component: Component, ...rest}) => (
<Route {...rest} render={props => (
window.globalState.isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{
pathname: '/signin',
state: {from: props.location}
}} />
)
)} />
)
Yeah i know a bit late .
Visual studio 2019
import React from 'react';
import { Container } from 'reactstrap';
import NavMenu from '../components/NavMenu';
export default props => (
<div>
{window.location.pathname !== '/login' ? <NavMenu /> : null}
<Container>
{props.children}
</Container>
</div>
);
i hope somebody helps out there.. !!! Happy coding
I made some solution while solving the problem.
First You can wrap the Switch in a website header and footer
<BrowserRouter>
<WebsiteHeader />
<Switch>
<Route/>
<Route/>
<Route/>
</Switch>
<WebsiteFooter/>
<BrowserRouter>
then inside the header or footer wrap the components using withRouter from 'react-router-dom' so you can access the routes props
const WebsiteHeader = props => {
if (props.location.pathname == "/register") return null;
return (
<Fragment>
<DesktopHeader {...props} />
<MobileHeader {...props} />
</Fragment>
);
};
export default withRouter(WebsiteHeader);
Use render
<ConnectedRouter history={history}>
<Switch>
<Route path="/dashboard" render={props => <Layout><Dashboard {...props} /></Layout>} />
<Route path="/login" component={Login} />
</Switch>
</ConnectedRouter>
For forcefully refresh Header inside routing.
use forceRefresh={true}
const Routing = () => {
return(
<BrowserRouter forceRefresh={true}>
<Header/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/list/:id" component={ListingApi}/>
<Route path="/details/:id" component={HotelDetails}/>
<Route path="/booking/:hotel_name" component={PlaceBooking}/>
<Route path="/viewBooking" component={ViewBooking}/>
<Route exact path="/login" component={LoginComponent}/>
<Route path="/signup" component={RegisterComponent}/>
</Switch>
<Footer/>
</BrowserRouter>
)
}
I would just create a few different layouts one with header and footer and one without. And then instead of wrapping everything into one layout. I'd just do this wrapping inside each page component. So your components would be like:
Dashboard component
<SimpleLayout>
<Dashboard>
</SimpleLayout>
Home component
<MainLayout>
<Home>
</MainLayout>
Try like this
<Route path="/" render={(props) => (props.location.pathname !== "/login") &&
<Header />}>
</Route>
<Route path="/" render={(props) => (props.location.pathname !== "/login") &&
<Menu />}>
</Route>
<PrivateRoute path="/scope" component={Scope} ></PrivateRoute>
<Route exact path="/login" component={Login} />
In this example I'm checking the URL, If the URL is "/Login" I'm removing Menu and header component
For forcefully refresh Header inside routing.
const Routing = () => {
return(
<BrowserRouter forceRefresh={true}>
<Header/>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/list/:id" component={ListingApi}/>
<Route path="/details/:id" component={HotelDetails}/>
<Route path="/booking/:hotel_name" component={PlaceBooking}/>
<Route path="/viewBooking" component={ViewBooking}/>
<Route exact path="/login" component={LoginComponent}/>
<Route path="/signup" component={RegisterComponent}/>
</Switch>
<Footer/>
</BrowserRouter>
)
}

Nested <Route> components are not rendering properly in react-redux-router [duplicate]

I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
main.js
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public component with exact exact path='/' and then in the Public component you are matching for the other Routes. So if the route path is /signup, at first the path is not exact so Public component is not rendered and hence no subRoutes will.
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home and then in the child Route you wish to write /dashboard . It should be written like
<Route path="/home/dashboard" component={Dashboard}
or even better
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}

Categories

Resources