Prashant Shishodia
Prashant Shishodia

Reputation: 41

React App just shows the starting page on Github pages

I create a react app, that has multiple routes, which works correctly on localhost. But when I deploy it on github pages using npm run deploy only the homepage is shown.

Details : The app is named, cp-tools. When I open username.github.io/cp-tools/ I get the homepage as expected, but when I open say,username.github.io/cp-tools/problem-filter/or any other page github says, 404 page not found.

Routing (App.js):

    <div className="App">
      <NavBar />
      <BrowserRouter basename ={process.env.PUBLIC_URL}>
        <Switch>
          <Route exact path = '/' component = {Home} /> 
          <Route exact path = '/problem-filter' component = {ProblemFilter} /> 
          <Route path = '*' component = {NotFound} /> 
        </Switch>
      </BrowserRouter>
    </div>

package.json :

{
"homepage": "https://pshishod2645.github.io/cp-tools",
// other details
}

Upvotes: 0

Views: 923

Answers (2)

Rameshkumar
Rameshkumar

Reputation: 260

You need to use an exact path for / home component only. If you put exact keyword for all router component its takes first component.

<Route exact path="/" component={Home} />

follow below line code : Routing (App.js):

 <div className="App">
      <NavBar />
      <BrowserRouter basename ={process.env.PUBLIC_URL}>
        <Switch>
          <Route exact path = '/' component = {Home} /> 
          <Route path = '/problem-filter' component = {ProblemFilter} /> 
          <Route path = '*' component = {NotFound} /> 
        </Switch>
      </BrowserRouter>
    </div>

Upvotes: 0

Jackyef
Jackyef

Reputation: 5012

The way GitHub pages works is that, request to an URL username.github.io/cp-tools, will be served by the index.html file found in the github.com/username/cp-tools repository, IF the repository has gh-pages setup.

If you go to username.github.io/cp-tools/problem-filter on your browser, GitHub will fail to find any files matching that path, thus showing 404 errors. You can still navigate to that page from the entrypoint via client-side routing (using react-router-dom <Link />, history.push(), etc).

I would suggest looking into other static hosting service such as Netlify and Zeit Now for this requirement.

But, if you want to stay with GH pages, a workaround is to use hashHistory instead, which uses the # for defining path for your React app. You can read more about this here.

Upvotes: 0

Related Questions