Search code examples
reactjsurl-routingsingle-page-application

Routing in react using spa-github-pages - unable to send '/' and '/about' requests to About component


Using react-spagithubpages to publish this app to Github pages and I want my About component to answer calls for "/" and "/about" however I can only get it to show on one, a couple of attempts had the component duplicated on one page, or not at all.

Here's what I have:

App.js
<div className="container">
  <Header />
</div>

Header.js
<Switch>
  <Router>
    <Navbar >
      <Navbar.Brand>
        <Nav id="NavItem" style={brandStyle}>
          BRAND
        </Nav>
      </Navbar.Brand>
      <Navbar id="navButton">
        <Nav style={aListStyle}>
          <Link to="/about" id="NavItem" style={aStyle}>About.</Link>
          <Link to="/resume" id="NavItem" style={aStyle}>Resume.</Link>
          <Link to="/contact" id="NavItem" style={aStyle}>Contact.</Link>
        </Nav>
      </Navbar>
      <Route exact path="/" component={AboutComponent}/>
      <Route path="/about" component={AboutComponent}/>
      <Route path="/resume" component={ResumeComponent}/>
      <Route path="/contact" component={ContactComponent}/>
    </Navbar>
  </Router>
</Switch> 

And I've tried variations of the following:

1.

  <Route path='/' component={App}> // tried replacing App with {AboutComponent} or {Home}
    <IndexRoute component={AboutComponent}/>

    <Route path='/about' component={AboutComponent}/>
    <Route path='/resume' component={ResumeComponent}/>
    <Route path='/contact' component={ContactComponent} />
  </Route>

2.

<Router>
    {["/", "/about"].map(path => 
        <Route path={path} component={AboutComponent} />
    )}
</Router>

3.

<Router>
    <Route path="/(about|*|/)/" component={AboutComponent} />
</Router>
  1. Making my own routes.json file to no avail

The last thing I can think to do is to duplicate the AboutComponent and make a separate HomeComponent to send '/' requests to.

Edit: Vishal Sharma suggested using Redirect and it works.

<Redirect from='/' to='/about'/>

Solution

  • As per the comments and conclusions, there is not really a need of writing a separate route if the rendering component is same. In my opinion, Redirect serves better.

    Example: <Redirect from="/" to="/about"/>