Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

React Router cheat sheet

install dependency Hello World!


yarn add react-router-dom import {
BrowserRouter,
# or: npm i --save react-router-dom Route
} from 'react-router-dom'

const Hello = () => <h1>Hello world!</h1>

const App = () => (


<BrowserRouter>
<div>
<Route path="/hello"
component={Hello} />
</div>
</BrowserRouter>
)

// open: http://localhost:3000/hello

Switch Link
//Renders the first <Route> that matches the import { Link } from 'react-router-dom'
location.
const Links = ({ match }) => (
import { <nav>
BrowserRouter, <Link to="/">Home</Link>
Switch, <Link to={{ pathname: '/dashboard' }}>
Route Dashboard
} from 'react-router' </Link>
<Link replace to="/about">About</
const YourComponent = () => ( Link>
<BrowserRouter> </nav>
<Switch> )
<Route exact path="/"
component={Home}/> export default Links
<Route path="/about"
component={About}/>
<Route path="/:user"
component={User}/>
<Route component={NoMatch}/>
</Switch>
</BrowserRouter>
);

export default YourComponent


NavLink match
import { NavLink } from 'react-router-dom' const Dashboard = ({ match }) => (
<ul>
const Links = ({ match }) => ( <li>params:
<nav> {JSON.stringify(match.params)}</li>
<NavLink activeClassName="active" <li>isExact: {match.isExact.toString()}
to="/"> </li>
Home <li>path: {match.path}</li>
</NavLink> <li>url: {match.url}</li>
<NavLink activeClassName="active" </ul>
to="/dashboard"> )
Dashboard
</NavLink> <Route path="/dashboard"
<NavLink activeClassName="active" component={Dashboard}/>
to="/about">
About
</NavLink>
</nav>
)

export default Links

Copyright © 2018 - 2020


www.developer-cheatsheets.com

You might also like