Skip to content

Instantly share code, notes, and snippets.

@jasheloper
Last active March 7, 2021 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasheloper/3441e182e972de5d43b77496f5f380d8 to your computer and use it in GitHub Desktop.
Save jasheloper/3441e182e972de5d43b77496f5f380d8 to your computer and use it in GitHub Desktop.
React Router example

Install

npm install react-router-dom

Import

Into App.js:

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

Setting up Router

In App.js wrap <Router></Router> around the component routes.


Example:

<Router>    
  
  <div className="App">
  
  <Route path="/" exact component={Home} />
  <Route path="/about" component={About} />
  
  </div>
  
</Router>

Usage

Import:

import { Link } from "react-router-dom";

Wrap <Link></Link> around something that should be a link.

Example:

<Link style={navStyle} to="/">
 
 <li>Home</li>
        
</Link>

Notes

  • <Switch> or exact can be used to render out the components 1 at a time.

    • The only thing with switch is that you have to order the components a certain way, i.e. if path "/" is first...the other components will no longer render; as soon as it finds that route with the specific path it stops looking ...so the other components, you will never see if you try to go to the path; it will stop at "/". However, 'exact' is the easiest way since you don't have to re-order anything and can just add 'exact' on the specific component with path "/".
@jasheloper
Copy link
Author

jasheloper commented Feb 27, 2020

React Router allows you to create paths that render the components. When a user clicks a link, data doesn't have to get grabbed from a server, instead it simply renders the component to the screen - whatever path it's set to. (no refreshing or anything)

@jasheloper
Copy link
Author

@ghilasjku
Copy link

@jashloper the link to the repo does not work could you please publish it again.
Ps : thanks for your explication

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment