lowcrawler
lowcrawler

Reputation: 7549

How to get React to respond to subfolder URL requests?

I have a React app that utilizes routing sitting in a sub-folder. It is currently set up like this:

index.js:

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <BrowserRouter basename={process.env.PUBLIC_URL}>
                <App />
            </BrowserRouter>
        </Provider>
    </React.StrictMode>,
    document.getElementById('root')
);

App.js:

function App() {
    return (
            <MyApp/>
    );
}

export default withRouter(App)

MyApp.js: (non-routing parts removed)

function MyApp(props) {
    return (
        <Switch>
            <Route path="/camera/:cameraID" component={CameraDetails} />
            <Route path="/">
                <Dashboard cameraData={props.cameraData} />
            </Route>
        </Switch>
    );
}

The files reside on the webserver such that they serve out of www.domain.com/myapp

If a user goes to domain.com/myapp they get the Dashboard component as expected in the second route. From the Dashboard, if they click a given camera and go to domain.com/myapp/camera/12345 ... they get the CameraDetails with cameraID appropriately assigned.

However, if they hit refresh on this page... or if they go directly to domain.com/myapp/camera/12345 they get a 404 error.

It's as if the only way they can get to the routes is by entering through the 'main' page. How can I make it so people can directly reference the sub dirs? (ie: the users want to bookmark their own camera, not go through the dashboard every time)

Upvotes: 0

Views: 787

Answers (1)

lissitz
lissitz

Reputation: 546

You need to set up your server (e.g. Apache, nginx) so that any request to domain.com/myapp/* for a file/directory that doesn't exits returns domain.com/myapp/index.html.

There is more detailed info in the cra docs https://create-react-app.dev/docs/deployment/

Upvotes: 1

Related Questions