How to route React app in a subdirectory

Martin Novak
1 min readOct 16, 2018

∑Using React BrowserRouter can be tricky with subdirectories as the application may have hard time differentiating between directories and actual pages.

Supporting specific directory with React Router

Supporting a specific subdirectory with React Router is actually fairly easy using basename:

Dynamic basename with 0 to many subdirectories of variable names

My situation is more complicated. I am using webpack, which on my local environment does not need any subdirectories. That is then built and deployed to a remote server into a subdirectory. On top of that I actually don’t know the name of the directory.

Fortunately, it can be solved again by a simple function that works with window.location.pathname:

This code will support your local environment on http://localhost:8080/ as well as your production server after webpack build on www.domain.tld/subdirectory/. There is no problem with reloading pages or any other gotchas as far as I know.

Let me know if the solution works for you or if you find any concerns.

--

--

Martin Novak

Martin is a product manager at work, a software developer in his free time, and an entrepreneur at heart.