Search code examples
reactjsreact-routergithub-pages

React application deploy on a gitHub pages


Let me explain my problem. I have published my website using gitHub pages and what i got in the end was a clear page only with Header component. I use a React router in this project and I think the issue was caused by my path in browser. I attached code for better understanding.

APP Component

import './App.css';
import FirstPageWrapper from './components/FirstPage/PageWrapper/PageWrapper';
import {Route, Routes} from 'react-router-dom'
import Header from './components/FirstPage/Header/Header';
import PageWrapper from './components/Second page/CollectionPage/PageWrapper/PageWrapper';
function App() {
  return (
    <>
    <Header/>
    <Routes>
      <Route path='/' element={<FirstPageWrapper/>}/>
      <Route path='/collection' element={<PageWrapper />}/>
      <Route path='/activation' element={<h1>Activation page</h1>}/>
    </Routes>
    </>
    
  );
}

export default App;

pay attention to the URL

As you can see only Header component is outside of the router. Ive got planty of websites and i cant just enter https://vladaes.github.io/URL instead ofhttps://vladaes.github.io/moviewebsite/`. Thank you very much for your help


Solution

  • I see there are two thigs you should resolve for this to work.

    1. You need to wrap all Router components in a Router context provider. In your case, since you are hosting your page in a hosting service you don't fully manage, you might need to use the Hash Router provider.
    2. Set the basename of your app to /moviewebsite. This is a property of the Router provider. All routes will be relative to this one.

    The code would end like this:

    import './App.css';
    import FirstPageWrapper from './components/FirstPage/PageWrapper/PageWrapper';
    import {Route, Routes, HashRouter} from 'react-router-dom'
    import Header from './components/FirstPage/Header/Header';
    import PageWrapper from './components/Second page/CollectionPage/PageWrapper/PageWrapper';
    function App() {
      return (
        <HashRouter basename="/moviewebsite">
          <Header/>
          <Routes>
            <Route path='/' element={<FirstPageWrapper/>}/>
            <Route path='/collection' element={<PageWrapper />}/>
            <Route path='/activation' element={<h1>Activation page</h1>}/>
          </Routes>
        </HashRouter>
        
      );
    }
    
    export default App;