0

I managed to create a website for myself using ReactJS. Everything works fine except that my last addition of an Error Page turns out that is rendered underneath every other page that is rendered. I.e. if I go to /localhost:3000/blog where all the blog elements are rendered, underneath this and above footer the Error404 component is also rendered. Any advice so I can expand my so far limited knowledge? The app component is this:

const App = () => {
  return (
    <Router>
      <Switch>

        <Route exact path="/">
          <Home />
        </Route>
      
          <div className="appWrapper">
            <NavBar />


              <Route exact path="/blog">
                  <Blog />
              </Route>

              <Route exact path="/article/:id">
                        <Article />
                    </Route>

              <Route exact path="/contact">
                <ContactForm />
              </Route>
              
              <Route path="*">
                <Error404 />
              </Route>
              
            <Footer />
          </div>

      </Switch>
    </Router>
    
  )
}
1

1 Answer 1

1

You need to add another Switch wrapping your Route's to make sure only one Route will render at a time.

const App = () => {
  return (
    <Router>
      <Switch>

        <Route exact path="/">
          <Home />
        </Route>
      
          <div className="appWrapper">
            <NavBar />
              <Switch>
              <Route exact path="/blog">
                  <Blog />
              </Route>

              <Route exact path="/article/:id">
                        <Article />
                    </Route>

              <Route exact path="/contact">
                <ContactForm />
              </Route>
              
              <Route path="*">
                <Error404 />
              </Route>
              </Switch>
            <Footer />
          </div>

      </Switch>
    </Router>
    
  )
}

Here is a working example.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked mate!Thanks! Now I start getting it how these things work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.