DEV Community

Cover image for react-router a quick guide

react-router a quick guide

sabrinasuarezarrieta profile image sabrinasuarezarrieta ・2 min read

Dynamic routing is the type of routing used by react-router. Unlike static routing, this takes place at the moment our application is rendering. This is because react-router makes use of components to define its routes.
The components that are responsible for displaying the different paths always render. Sometimes they render a component and sometimes null, all depending on the location.

To define the different routes of our application, we can use the Route component. The function of this component is to choose what to render according to the current location identified in the path. This is the case we saw earlier, all Route components always render, but sometimes they render a component and other times they return null.

import React from 'react';
import logo from './logo.svg';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Principal from './pages/principal/principal';
import Login from './pages/login/login';
import './App.css';

function App() {
  return (
        <Route path="/principal" component={Principal} />
        <Route path="/" component={Login} />        

export default App;
Enter fullscreen mode Exit fullscreen mode

The way that you can navigate in your application is using the Link component, this causes a redirect to a different route than the current one. The path to which it redirects us replaces the current location in the browser's history, here I present a little example.

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './Layout.css';
class Layout extends Component {
  render() {
    return (
      <div className="Layout">
        <div className="link-container">
          <Link to="/page1" className="link">go page 1</Link>
        <div className="link-container">
          <Link to="/page2" className="link">go page 2</Link>
export default NavBar;
Enter fullscreen mode Exit fullscreen mode

I hope this will be helpful and thanks a lot for reading

Discussion (0)

Forem Open with the Forem app