`react` Two routes are output together

Viewed 67

I have made two routes.

The problem is that when I go into the 'Main' component, I also get a 'NotFound' page at the bottom.

What should I do? I've been trying everything for 10 hours and I'm not quite sure where I'm going wrong.

app.tsx

import NoProduct from './pages/Product/NoProduct'
import NotFound from './pages/NotFound/NotFound'
import { hot } from "react-hot-loader";
import { QueryClient ,QueryClientProvider } from 'react-query'
import { Route,BrowserRouter, Redirect, Switch, useLocation} from 'react-router-dom';
import Main from './pages/Main/Main'

function App() { 
  return (
    <div>
      <Switch>
        <QueryClientProvider client={queryClient}>
          <Route exact path="/" component={Main} />
          <Route path="*" component={NotFound} />
        </QueryClientProvider>
      </Switch>
    </div>
   ) 
 }


export default hot(module)(App);

index.tsx

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
  document.getElementById('root')
);
4 Answers

Issue

You are not rendering the Route components into the Switch, so the Switch is returning the QueryClientProvider which then renders routes inclusively like a Router would.

Solution

Move the Switch into the QueryClientProvider component so it can match and render single routes as expected.

function App() { 
  return (
    <div>
      <QueryClientProvider client={queryClient}>
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="*" component={NotFound} />
        </Switch>
      </QueryClientProvider>
    </div>
  ) 
}

change the route path, * means anything, so it will get rendered too with first route

<Route path="/error" component={NotFound} />

or second solution would be, using exact, i hope this will work too

<Route exact path="*" component={NotFound} />

better solution wouldbe wrapping Switch with QueryClientProvider

You can wrap your Switch component from BrowserRouter component, then your code should work,

here is the example:

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Main} />
    <Route path="*" component={NotFound} />
  </Switch>
</BrowserRouter>

And if you're using the BrowserRouter component, then your QueryClientProvider causing the issue, move it outside the Switch then it should work.

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Main} />
    <Route path="/error" component={NotFound} />

    <Redirect to="/error" />
  </Switch>
</BrowserRouter>

Related