React Router: a library to manage routing in your single page app (SPA)
- history: library used to parse changed URLs and pass to react-router
- browserRouter: looks at the url to decide which components to show on the screen // CHART FOR REACT ROUTER
- setup
- Rending Components Conditionally
- Linking Routes
- Linking the Navbar
- Route Props
- Dynamic Routes
- history.push
- Route
$ npm install --save react-router-dom
- wrap Router around the application to allow for routing
- in
index.js
:import { BrowserRouter as Router } from 'react-router-dom'; ReactDOM.render( <Router> <App /> </Router>, document.getElementById('root') );
- conditionally renders based on the URL
- in
App.js
import { Switch, Route } from 'react-router-dom'; <div className="App"> <Route path='/' component={Navbar} /> <Switch> /* routes will go here */ </Switch> </div>
- a component that provides config for showing certain components depending on the URL path
path
- specifies the url path- can use
component
,render
orchildren
to specify the component- using
component
- specifies a react component to be rendered depending on thepath
<Route path='/' component={Home} />
- using
render
- similar to component, but the value is a function that can pass down extra propsconst projects = ["project 1", "project 2", "project 3"]; <Route path='/portfolio' render={() => ( <Portfolio projects={projects} /> )} />
- using
- an anchor tag, when you click on it, it uses the history object to change the url
import {Link} from 'react-router-dom'; <Link className="btn" to="/">home</Link>
- similar to link, but for navigation
<NavLink className="home" exact style={defaultStyle} activeStyle={active} to='/'> <li >Home</li> </NavLink>
- match: info about how the url matches the router
- location: location where you are now (similar to window.location)
- history: allows explicit changes to the url (similar to HTML5 history object)
- allows you to make dynamic routes
- to make the param optional - add a
?
// app.js <Route exact path='/:name?/' component={Home} /> // home.js <div>Welcome {this.props.match.params.name}</div>
- if a component is not rendered inside of a Route component, you can use withRouter to get route props
import {withRouter} from 'react-router-dom' /* ... */ <button onClick={() => this.props.history.push('/')}> /* ... */ export default withRouter(DataProvider);
- to pass custom props: use
render
, else usecomponent
- with
component
import { Route } from 'react-router-dom'; <Route path='/about' component={About} />
- with
render
you can add custom props
// props arg: passes the match, location, and history props to the component <Route path='/portfolio' render={props => ( <Portfolio {...props} projects={projects} /> )} />
- with