DEV Community

loizenai
loizenai

Posted on

React Router v4 example

https://grokonez.com/frontend/react/react-router-example-v4

React Router v4 example

In this tutorial, we're gonna look at React example that uses Router v4 for implementing navigation.

Goal

We will use React Router v4 to create a navigation bar in which, clicking on any item will show corresponding Component without reloading the site:

react-router-example-goal

How to

Project Structure

react-router-example-structure

Install Packages

We need react-router-dom to apply Router. Add it to dependencies in package.json:


{
  ...
  "dependencies": {
    ...
    "react-router-dom":"4.2.2",
  }
}

Then run cmd yarn install.

Configure Webpack

Open webpack.config.js:


const path = require('path');

module.exports = {
    ...
    module: {
        rules: [...]
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true
    }
};

historyApiFallback option is specifically for webpack-dev-server. Setting it true will effectively ask the server to fallback to index.html when a requested resource cannot be found (404 occurs).

Create Components

  • For each Page that displays when clicking on Navigation item, we add one Component. So we have 4 Components: Dashboard, AddBook, EditBook, Help.
  • We need a Component for 404 status, it's called NotFound.
  • Now, we put a group of NavLink in header of Header Component:

More at:

https://grokonez.com/frontend/react/react-router-example-v4

React Router v4 example

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay