How to set a base url for react-router at the app level?

Fabrice picture Fabrice · Jan 7, 2018 · Viewed 26.9k times · Source

I have an app created with create-react-app that I want to install in a subdirectory on my website. The recommended way is to add process.env.PUBLIC_URL as the baseurl. ie:

<Route exact path={`${process.env.PUBLIC_URL}/signin`} component={SigninPage}/>

Now is there a way I can set it at the app level so I don't have to duplicate this piece of code on every Routes or Links or NavLinks?

Thanks!

Answer

margaretkru picture margaretkru · Jan 7, 2018

You can set it as basename on your Router, here are links to the react router docs: basename in BrowserRouter and basename in HashRouter. It would look something like this:

<Router basename={process.env.PUBLIC_URL}>
</Router>