Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React router appends page at last when routing

I have two components, {App} and {Blog}, when I was trying to route to Blog page from App, actually the Blog page content was appended at the last of App page. How can I jump to the blog page from App page?

Routing:

const routes = (
  <BrowserRouter>
    <div>
      <Route path="/" component={App}/>
      <Route path="blog" component={Blog}/>
    </div>
  </BrowserRouter>
);


Meteor.startup(() => {
  ReactDOM.render(routes, document.querySelector(".render-target"));
});

Blog.js:

class Blog extends Component{
  render(){
    return(
      <div>Blog</div>
    );
  };
}

export default Blog; 
like image 353
Han Avatar asked Mar 08 '23 23:03

Han


1 Answers

You need to use the Switch component from react-router. This will make sure that the first route matches inside.

<BrowserRouter>
    <Switch>
      <Route path="blog" component={Blog}/>
      <Route path="/" component={App}/>
    </Switch>
</BrowserRouter>

As you can see in the example, put the blog route before the /. If you put the / route as your first route it will match this one on any other route and stop there.

For more info, check out this piece

like image 191
Sebastiaan van Arkens Avatar answered Mar 11 '23 12:03

Sebastiaan van Arkens