Gitlab Pages and React Router
Asked Answered
M

1

10

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();
Marche answered 11/10, 2017 at 9:28 Comment(2)
Do you use HashRouter or BrowserRouter?Upright
I changed to HashRouter. It works. Thank you.Marche
N
19

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.

Naive answered 7/12, 2017 at 5:39 Comment(5)
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?Ahlgren
@VictorSuzdalev Follow the link. 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 existsNaive
whoa, thank you! This idea hadn't occured to me, but seems pretty much what I need!Ahlgren
what about the homepage key on the package.json?Selma
Very clever solution. Note that instead of copying the index, you can redirect everything (including the 404 page) to the index: docs.gitlab.com/ee/user/project/pages/…. A simple line echo '/* /index.html 200' > public/_redirects does the job.Rodent

© 2022 - 2024 — McMap. All rights reserved.