I want to create a prefix for some paths in React Router v4, such as v1
in front of all my routes for version 1 of my app. Here's what I've tried:
<BrowserRouter>
<Switch>
<App path="v1" >
<Switch>
<Route path="login" component={Login} />
<Route component={NotFound} />
</Switch>
</App>
<Route component={NotFound}/>
</Switch>
</BrowserRouter>
Here's App
:
import React, { Component } from 'react';
import logo from '../Assets/logo.svg';
import '../Assets/css/App.css';
class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default App;
Currently I am using this approach but it doesn't seem to working.
When I go to http:\\localhost:3000\v1\login
it shows the NotFound
component.
Any help here?
BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.
Import react-router functions import { BrowserRouter as Router, Route } from "react-router-dom"; const Home = () => { return ( <div> <h1>Home! </h1> </div> ); }; // Step 2. Changed to have router coordinate what is displayed ReactDOM. render( <Router> <Route path="/" component={Home} /> </Router>, document.
Routing to the 404 PageYou specify the URL path and the element you want to render at that route. The 404 page displays for paths that don't exist on the website. So, instead of specifying the path, use an asterisk (*). Using * renders the NotFound component for all the URLs not specified in routes.
Came across a similar problem. Ended up using <BrowserRouter basename='/v2'>
https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string
Instead of using App
as a container, restructure your routes like so:
<BrowserRouter>
<Switch>
<Route path="/v1" component={App} />
<Route component={NotFound}/>
</Switch>
</BrowserRouter>
This will make App
render whenever you navigate to /v1
or /v1/whatever
. Then, in App
, instead of rendering children, render your other routes:
render() {
const { match } = this.props;
return (
<Switch>
<Route path={`${match.url}/login`} component={Login} />
<Route component={NotFound} />
</Switch>
);
}
Thus, App
will render a Switch
with two possible routes. match.url
here is v1
because it matched the URL part v1
. Then, it creates a route with ${match.url}/login
which results in v1/login
. Now, when you navigate to v1/login
you'll get the Login
component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With