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?