1

Here is the function that returns my routes:

...
import { Route, Switch, Redirect } from "react-router-dom"
import { ApolloProvider } from "@apollo/client";
import { MuiThemeProvider } from '@material-ui/core/styles';
...

function Routes(props) {
  return (
      <Switch>
        <Route path="/" exact component={MainPage} />
        <Route path="/page1" exact component={PageOne} />
        <Route path="/page2" exact component={PageTwo} />

        <MuiThemeProvider theme={theme}>
          <Route path="/page3" exact component={PageThree} />

          <ApolloProvider client={client}>
            <Route path="/page4" exact component={PageFour} />
          </ApolloProvider>
        </MuiThemeProvider>
        <Redirect from="*" to="/" />
      </Switch>
  );
}

I want to redirect invalid urls to main page but this code is not working. I tried moving <Redirect> to inside of MuiThemeProvider and ApolloProvider but this time it redirects all routes, except pageone and pagetwo, to main page. How can I use redirect properly in this case ?

"react": "^16.12.0"
"react-router-dom": "^5.1.2"
"@material-ui/core": "^4.9.2"
Buzzinga
  • 401
  • 3
  • 9
  • 2
    All children of a `` should be `` or `` elements. Probably a duplicate of [React router doesnt reach redirect](https://stackoverflow.com/a/66785774/2873538). – Ajeet Shah May 07 '21 at 13:12
  • Seconded, a Provider is not a valid child of a `Switch` and will break it. The `from="*"` is also pointless since the default behaviour is to match any route. – lawrence-witt May 07 '21 at 13:24
  • Thank you both. It seems I need to refactor the code related to providers. – Buzzinga May 07 '21 at 16:26

1 Answers1

0

Try this:

<Route path="*"><Redirect to="/" /></Route>

And pass exact prop to your all other routes. For example,

<Route exact path="/page2" exact component={PageTwo} />
Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43