2

There are three route components. Navbar is always visible and it works fine. The main page, Home, works too and I can click the link to Checkout, but on the Checkout page I can't see any text, images, or anything except the blank background (as well as the Navbar). When I try to wrap the gradient background div around Checkout, it also doesn't work. Renaming the path of Checkout doesn't help as well.

import React from "react"
import './App.css'
import Navbar from './navbar'
import Home from './Home'
import Checkout from "./Checkout"
import { BrowserRouter as Router, Switch, Route } from "react-router-dom"

function App() {
  return (
    <Router>
      <div className="App">
        <Navbar />
        <Switch>
          <div className="gradient__bg">
          <Route exact path='/' component={Home}>
            <Home />
          </Route>
          </div>
          <Route path='checkout' component={Checkout}>
            <Checkout />
          </Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;
hirat3
  • 23
  • 6

2 Answers2

2

The issue is that the Switch only renders the first matched Route or Redirect component, but you've wrapped one of the Route components in a div element which breaks this abstraction and will always be rendered, so if there are routes after the div they won't ever be able to be matched and rendered. This means the checkout route/path is never rendered.

To resolve, move the wrapper div inside the Route component.

Also, don't specify the component prop and provide children components. You can either wrap the child component

<Route path='/'>
  <div className="gradient__bg">
    <Home />
  </div>
</Route>

or use the render prop and forward the route props to the Home component

<Route
  path='/'
  render={props => (
    <div className="gradient__bg">
      <Home {...props} />
    </div>
  )}
/>

Note: Within the Switch component path order and specificity matter, you should order the routes from more specific paths to less specific paths. Don't forget that the Checkout component's path should include the leading "/", i.e. it should be "/checkout".

<Router>
  <div className="App">
    <Navbar />
    <Switch>
      <Route path='/checkout'>
        <Checkout />
      </Route>
      <Route path='/'>
        <div className="gradient__bg">
          <Home />
        </div>
      </Route>
    </Switch>
  </div>
</Router>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
1

Just make checkout route above the home route

   <Route path='checkout' component={Checkout}>
        <Checkout />
      </Route>
      <Route exact path='/' component={Home}>
        <Home />
      </Route>
samar
  • 66
  • 3