React router not working in URL bar, but it still works with <Link> tags

Viewed 599

So I have a route like in the documentation: <Route path="*"><Redirect to={'/'}/></Route>. To make sure that all routes lead to '/' if the route doesnt exists.

All my routes work with a <Link> tag but not when I type them in the URL bar.

How can this be? I cant find information about this online.

index file:

    return(
  <Fragment>
    <BrowserRouter basename={`/`}>
    <Switch>
        <App>
            <TransitionGroup>
                {routes.map(({ path, Component }) => (
                    <Route key={path} exact path={`${process.env.PUBLIC_URL}${path}`}>
                        {({ match }) => (
                            <CSSTransition in={match != null} timeout={100} classNames={anim} unmountOnExit>
                                <div><Component/></div>
                            </CSSTransition>
                        )}
                    </Route>
                ))}

                <Route exact path="*"><Redirect to={'/'}/></Route>

            </TransitionGroup>
        </App>
    </Switch>
    </BrowserRouter>
  </Fragment>
  )

Route file:

export const routes = [
    {
            path:`/`,
            Component:Home
    },
    {
            path:`/login`,
            Component:Login
    },
    {
            path:`/signup`,
            Component:Signup
    },
    {
            path:`/event/:name`,
            Component:Event
    },
    {
            path:`/create-event`,
            Component:CreateEvent
    },

]

Link tag:

<Link to={"/event/" + events[i].name} className="text-dark">
2 Answers

From the react-router documentation,

All children of a <Switch> should be <Route> or <Redirect> elements. Only the first child to match the current location will be rendered.

I can see <Route> is not a direct or first child to <Switch>

Use Switch from react-router to renders the first child that matches the location. And be sure to keep, all the known routes before * to avoid redirection to the / path. Following is an example, for your case.

import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect,
} from "react-router-dom";

class App extends React.Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={() => <div>{"MAIN"}</div>} />
          <Route
            exact
            path="/event/:name"
            component={() => <div>{"SELECTED EVENT"}</div>}
          />
          <Route exact path="*" component={() => <Redirect to={"/"} />} />
        </Switch>
      </Router>
    );
  }
}

export default App;

Hope this would solve your issue.

Related