0

I recently implemented the react-router Switch component into my routes in order to render a NoMatch component (which is just a 404 error component). However, after implementing this into my routes I noticed that on my home page only 1 component will render, the Heading component.

Both Heading and SearchBar should render to the same path.

My code below:

const routes = [
  {
    path: "/",                   
    exact: true,
    component: () => <Heading />
  },
  {
    path: "/",                      
    exact: true,
    component: () => <SearchBar />
  },
  {
    component: NoMatch
  }
];

class App extends Component {

  render() {
    return (
      <div>
        <BrowserRouter>
          <div>
            <MenuBar />
            <Switch>
              {routes.map((route, index) =>
                <Route
                  key={index}
                  path={route.path}
                  exact={route.exact}
                  component={route.component}
                />
              )}
            </Switch>
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

I noticed if I remove the Switch component then everything will render just fine, but then the NoMatch component will also render to the route.

Question: Why can't I render multiple components on the same path inside of Switch? How can I fix this problem when I need to render both Heading, and SearchBar component on the "/" path?

2 Answers 2

2

I think you are missing how Switch works.

Switch will start looking for a matching Route, whenever it will find a match it will stop looking for matches and render that particular component.

Always define unique routes, if you want to render multiple component for same path then wrap all of them by a div.

Write it like this:

const routes = [
  {
    path: "/",                   
    exact: true,
    component: () => <div> <Heading /> <SearchBar /> </div>
  },
  {
    component: NoMatch
  }
];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for solving another one of my issues, yet again lol!
0

The Switch component only allows one route - basically each child route has an implicit exact attribute.

So you need to remove it for your purposes, and your experimentation confirms that

Comments

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.