Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 365
Fabrice Avatar asked Jan 07 '18 06:01

Fabrice


People also ask

How do I change base URL in React app?

In your package. json file change the homepage entry to a relative path, excluding any sub-domain/nested directory. Save this answer.

How do I add a link to my router in React?

To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.


1 Answers

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>
like image 50
margaretkru Avatar answered Sep 19 '22 21:09

margaretkru