Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gitlab Pages and React Router

I will use Gitlab Pages. It seems that Gitlab Pages doesn't work with React Router. I get an empty page. How can I use gitlab Pages with react Router? How can I solve this problem?

/src/App.js

import React from 'react';
import { Route } from 'react-router-dom';
import HomePage from './components/pages/HomePage';
import LoginPage from './components/pages/LoginPage';

const App = () => (
  <div>
    <Route path="/" exact component={HomePage} />
    <Route path="/login" exact component={LoginPage} />
  </div>
);

export default App;

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);
registerServiceWorker();
like image 722
Aaron Avatar asked Oct 11 '17 09:10

Aaron


People also ask

Can I use react Router in GitHub pages?

So now we can deploy our react-router app to Github pages. You can refer to this GitHub repository for the deployment. Just make sure your homepage URL (project repository name) in package. json is the same as the homepage path.

Is react Router deprecated?

Thus, we found that a lot of the packages were deprecated and needed to be replaced ASAP. One of the biggest surprises for us was the deprecation of react-router-redux .


1 Answers

HashRouter is one solution. But, you can still use the BrowserRouter

Short Answer

// In your src/index.js,
<BrowserRouter basename={process.env.PUBLIC_URL}>
    <App />
</BrowserRouter>

And for the environment variable, open your .gitlab-ci.yml and add the following.

variables:
    PUBLIC_URL: "/your-project-name" # slash is important

Also in your .gitlab-ci.yml, in the stage where you deploy the page, add the following to the script section:

- cp public/index.html public/404.html

Explanation

If your project name is ABC, the gitlab page url would be https://{username}.gitlab.io/ABC But, react router expects the base url to be https://{username}.gitlab.io/. So, you need to explicitly tell the ReactRouter about the basename.

The 404.html is needed to allow the user to directly navigate to all of your routes. Without it, GitLab has no idea that your client-side routing is located in your index.html, and will serve the default 404 page.

like image 61
Mo... Avatar answered Nov 15 '22 04:11

Mo...