Link to other pages in React

Posted on

in

,

First you will need react-router-dom. Install it using:

$ npm install --save react-router-dom

Here is the code that directs you to each page:

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import Home from "./pages/Home";
import Websites from "./pages/Websites";
import Error from "./pages/Error";
import './App.scss';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div>
          <Switch>

            <Route path="/" component={Home} exact />
            <Route path="/websites" component={Websites} />
            <Route component={Error} />
          </Switch>

        </div>
      </BrowserRouter>
    );
  }
}

export default App;

BrowserRouter is the container. Switch will find and render the first page that matches the path/url.

Link to the pages using NavLinks:

import React from 'react';

import { NavLink } from 'react-router-dom';

class Navigation extends React.Component {

    render() {

        return (
            <>
                <NavLink to="/">Home</NavLink>
                <NavLink to="/websites">Websites</NavLink>
                </div>
            </>
        )
    }
}

export default Navigation;

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930