Understanding Client-Side Routing — React Router 101

What is Routing?

Client-Side Routing

Setting Up React-Router

<Router>
<App/>
</Router>

Route Component

import {Route} from "react-router-dom"
// Route will render its children if the path matches
<Route path="/someendpoint">
<Component prop1="something"/>
</Route>
// Route will render the component passed via the component prop, passing it the router props when the path matches
<Route path="/someendpoint" component={Component}/>
// Route will render the return value of the function passed in the render prop, passing the routerprops as an argument to that function. This occurs when the path matches.
<Route path="/someendpoint" render={(renderProps) => {
return <Component {...renderProps} prop1="something">
}}/>

Link and history.push

Link

import {Link} from "react-router-dom"
<Link to="/someendpoint">
<button>Click Me</button>
</Link>

History.push

const Component = (props) => {    // ref for grabbing the value of the input form (uncontrolled forms)
const inputRef = React.useRef(null)
// function for when form is submitted
const handleSubmit = (event) => {
// prevent form from refreshing the page
event.preventDefault()
// log the value of the input
console.log(inputRef.current.value)
// push user back to the main page
props.history.push("/")
}
}

Switch

import {Switch} from "react-router-dom"
<Switch>
<Route path="/" render={(renderProps) => {
return <MainPage {...renderProps} prop1="something">
}}/>
<Route path="/second" render={(renderProps) => {
return <SecondPage {...renderProps} prop1="something">
}}/>
<Route path="/third" render={(renderProps) => {
return <ThirdPage {...renderProps} prop1="something">
}}/>
</Switch>
<Switch>
<Route exact path="/" render={(renderProps) => {
return <MainPage {...renderProps} prop1="something">
}}/>
<Route path="/second" render={(renderProps) => {
return <SecondPage {...renderProps} prop1="something">
}}/>
<Route path="/third" render={(renderProps) => {
return <ThirdPage {...renderProps} prop1="something">
}}/>
</Switch>

URL Params

<Route path="/third/:myParam" render={(renderProps) => {
return <ThirdPage {...renderProps} prop1="something">
}}/>

Conclusion

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store