9

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();
Aaron
  • 769
  • 1
  • 14
  • 25

1 Answers1

16

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.

V Maharajh
  • 9,013
  • 5
  • 30
  • 31
Mo...
  • 1,812
  • 2
  • 17
  • 22
  • Do you know, is it possible to configure gitlab pages to some sort of 'history fallback' mode, so index.html would be served for any sub-route? – Victor Suzdalev Jun 11 '18 at 17:15
  • 4
    @VictorSuzdalev Follow the [link](https://github.com/rafrex/react-github-pages). The idea is that GitHub Pages allows to set up custom 404.html page. And add a script to redirect to the route where `index.html` exists – Mo... Jun 12 '18 at 18:02
  • whoa, thank you! This idea hadn't occured to me, but seems pretty much what I need! – Victor Suzdalev Jun 13 '18 at 11:38
  • 2
    what about the homepage key on the package.json? – ValRob Sep 24 '19 at 17:28
  • Very clever solution. Note that instead of copying the index, you can redirect everything (including the 404 page) to the index: https://docs.gitlab.com/ee/user/project/pages/redirects.html#rewrite-all-requests-to-a-root-indexhtml. A simple line `echo '/* /index.html 200' > public/_redirects` does the job. – Boiethios Dec 08 '22 at 17:03