Skip to content
Advertisement

Mutliple components rendered in React JS using Router

I have tried using <Switch> and exact after viewing this post: React Router v4 renders multiple routes but it hasn’t resolved my problem, which is that 2 of my components are rendered at the same time when the <Link> function operates.

The code:

import React from "react";
import '../styles/Onboarding.css';
import {Link, Route, BrowserRouter as Router, Switch } from "react-router-dom";

function ComponentA() {

  return (
    <Router>
      <div className="parent">
        <h1 className="title">title</h1>
        <p className="description">description</p>
        <Link exact to="/componentB"><button className="button">enter</button></Link>
        <Switch>
          <Route exact path="/componentB" component={ComponentB} />
        </Switch>
      </div>
    </Router>
  );
}


function ComponentB() {
  return (
    <div>
      Welcome to ComponentB
    </div>
  )
}

export default ComponentA;

The result is the html of Component A showing up and “Welcome to ComponentB” underneath them. Please help me out with this reaact-router issue

Advertisement

Answer

Contents of ComponentA shows up because ComponentB is now a child route of ComponentA. To render them separately, need a parent component like this:

export default function App() {
  return (
    <Router>
        <Switch>
          <Route exact path="/componentA" component={ComponentA} />
          <Route exact path="/componentB" component={ComponentB} />
        </Switch>
    </Router>
  );
}

Edit focused-neumann-mm8qb

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement