Skip to content

Instantly share code, notes, and snippets.

@VPAbraham
Last active October 19, 2019 21:59
Show Gist options
  • Save VPAbraham/f083c183c7102736b58732f847157edc to your computer and use it in GitHub Desktop.
Save VPAbraham/f083c183c7102736b58732f847157edc to your computer and use it in GitHub Desktop.
react-router-intro

React Router quick start

Install into React project by running

npm install react-router-dom

in App, import:

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

you can rename longer import by the example of 'BrowserRouter' above.

Rather than placing components directly into App, they are established as routes.

Example:

The entire return JSX for App will be wrapped in <Router></Router> tags

function App() {
  return (
    <Router>
      <div className="App">
        <Nav />
        <Switch>
          <Route path="/" component={Home}/>
          <Route path="/about" component={About} />
          <Route path="/shop" component={Shop} />
        </Switch>
      </div>
    </Router>
  );
}

Decide which component is on each route by adding component={yourComponentName}

Also, establish which path it is set at from the root URL by path="/yourComponent"

The above code has an issue to check to see if path has a / for the first item. This causes issues with Routes becoming combined due to the path="/"

How to remedy this issue:

Enclose the Routes in <Switch></Switch> Now the routes wont be combined but it will stop at the first component that fulfills any part of its search criteria.

By adding exact into the component properties, it will only go to Routes that exactly match the URL directory name. <Route path="/" exact component={Home}/>

How to switch between routes

To be able to click between routes rather than having to enter the path into the browser, go to your navigation component and import { Link } from 'react-router-dom'

Then, in the Nav component, we wrap the li's where the links would go in tags.

To direct these Links to the proper page, we would give them the property to="/myComponent"

Ex:

function Nav() {
  return (
    <nav>
      <h3>Logo</h3>
        <ul className="nav-links">
          <Link to='/about'>
            <li>About</li>
          </Link>
          <Link to='/shop'>
            <li>Shop</li>
          </Link>           
        </ul>
    </nav>
  );
}
@peeratmac
Copy link

Wow, thank you!

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