peter flanagan
peter flanagan

Reputation: 9830

react router url issues after deployment

I am using React router to change routes. This works well when I develop locally.

My router code looks like this and everything works perfectly.

<Router>
    <Route exact path="/" render={(routeProps)=> <Homepage {...routeProps} />}/>
    <Route path="/graph" render={(routeProps)=> <AboutPage {...routeProps} />}/>            
</Router>

The issue I am having is when I deploy it to my github page, http://exampleuser.github.io/react-project.

As the project is in a react-project folder this "/" refers to the actual route which is http://exampleuser.github.io/

Can anyone advise how the path should look so it works when deployed?

Upvotes: 4

Views: 6534

Answers (2)

jerryurenaa
jerryurenaa

Reputation: 4712

it's an easy fix I came across the same issue here is how I fixed it.

1- go to your root directory in your cPanel or server if you are using apache. and create a .htaccess file

open the file and add the following code to it.

#jerryUrena is awesome RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]

after this, your website should work the same way.

Upvotes: 0

Carlos Valencia
Carlos Valencia

Reputation: 7003

You can use the basename prop in your router, just make sure you only use that in production and not in development (you could use environment variables for that) your router should look like this:

<Router basename="your-react-project">
  {/* routes */}
</Router>

If you are using create_react_app, you can just use the env variable process.env.PUBLIC_URL like this (which is empty en development so it will work fine for bot dev and production):

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

I actually have a project running with this configuration and works just fine.

Upvotes: 8

Related Questions