Aaron
Aaron

Reputation: 839

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();

Upvotes: 10

Views: 7309

Answers (1)

Mo...
Mo...

Reputation: 1961

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.

Upvotes: 19

Related Questions