DEV Community

Colin Swinney
Colin Swinney

Posted on

Help with React Router 404 within React Transition Group

I'm having difficulty implementing a 404 Component combining React Router with React Transition Group. My "NoMatch" component will not get rendered while inside a CSSTranisitionGroup. I have tried moving the CSST Group to within the Routes of Switch, but this doesn't seem to solve the issue. How can I successfully create a 404 page using CSST Group? Please see this attached Sandbox as well: Sandbox Link

import React from "react";
import { BrowserRouter, Route, Switch, NavLink } from "react-router-dom";
import { CSSTransition } from "react-transition-group";
import "./styles.css";
import Home from "./Home";
import About from "./About";
import Contact from "./Contact";
import NoMatch from "./NoMatch";

const Data = {
  routes: [
    {
      path: "/",
      exact: true,
      title: "Home",
      navTitle: "Home",
      contentClass: "home",
      Component: Home
    },
    {
      path: "/about",
      exact: true,
      title: "About",
      navTitle: "About",
      contentClass: "about",
      Component: About
    },
    {
      path: "/contact",
      exact: true,
      title: "Contact",
      navTitle: "Contact",
      contentClass: "contact",
      Component: Contact
    }
  ]
};

export default function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <nav>
          <ul>
            {Data["routes"].map((route, i) => (
              <li key={i}>
                <NavLink
                  className={"nav-link"}
                  exact={route["exact"]}
                  to={route["path"]}
                >
                  {route["navTitle"]}
                </NavLink>
              </li>
            ))}
          </ul>
        </nav>

        {Data["routes"].map((route, i) => (
          <Route key={i} exact path={route.path}>
            {({ match }) => (
              <CSSTransition
                in={match != null}
                timeout={1000}
                classNames={`${route.contentClass} page`}
                unmountOnExit
              >
                <Switch>
                  <Route render={() => <route.Component {...route} />} />
                  <Route component={NoMatch} />
                </Switch>
              </CSSTransition>
            )}
          </Route>
        ))}
      </BrowserRouter>
    </div>
  );
}

Top comments (1)

Collapse
 
greggcbs profile image
GreggHume

You cant use a swtich with CSS transition. I am facing an issue with this because I need a 404 page but now it is showing on every page cause the lack of a switch is causing the router to carry on looking for pages after it has found one.

Did you solve this at all?