Hinesh Patel
Hinesh Patel

Reputation: 1251

React Router v4 path not matched issue

I am trying to render a 404 page when a path which I enter in the URL doesn't exist.

Here is my router.jsx:

const NotFoundLayout = () => (
  <div><h1>Not Found</h1></div>
);

const DefaultLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

DefaultLayout.propTypes = ({
  component: PropTypes.func.isRequired,
});

const BlogLayout = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={matchProps => (
      <div>
        <NavigationBar path="blog" />
        <div className="mainContent">
          <Component {...matchProps} />
        </div>
        <Footer />
      </div>
    )}
  />
);

BlogLayout.propTypes = ({
  component: PropTypes.func.isRequired,
});

const HomePath = () => (
  <Switch>
    <Route exact path="/" component={Home} />
  </Switch>
);

const NotFoundPath = () => (
  <Switch>
    <Route component={NotFoundLayout} />
  </Switch>
);

const Work = () => (
  <Switch>
    <Route exact path="/my-work" component={MyWork} />
    <Route path="/my-work/:workName" component={WorkShow} />
  </Switch>
);

const Blog = () => (
  <Switch>
    <Route exact path="/blog" component={PostIndex} />
    <Route path="/blog/search" component={PostSearch} />
    <Route exact path="/blog/:postName" component={PostShow} />
    <Route path="/blog/category/:categoryName" component={CategoryShow} />
    <Route path="/blog/tag/:tagName" component={TagShow} />
  </Switch>
);

const routes = (
  <div>
    <DefaultLayout exact path="/" component={HomePath} />
    <DefaultLayout path="/my-work" component={Work} />
    <BlogLayout path="/blog" component={Blog} />
    <DefaultLayout component={NotFoundPath} />
  </div>
);

export default routes;

The NotFoundLayout shows at the bottom of every component. How can I change this file so that it only shows when a path doesn't match?

Upvotes: 1

Views: 150

Answers (1)

pwolaq
pwolaq

Reputation: 6381

you should use <Switch> component in routes, as you did in Blog, Work and others

Upvotes: 2

Related Questions