📕
Dan Fitz's Notes
  • README
  • Ai
    • Supervised Machine Learning
      • Introduction To Machine Learning
      • Regression With Multiple Input Variables
      • Classification
  • Csharp
    • C Sharp Advanced
      • Generics
      • Delegates
      • Lambda Expressions
      • Events
    • C Sharp Fundamentals
      • Intro To C
      • Primitive Types And Expressions
      • Non Primitive Types
      • Control Flow
      • Arrays And Lists
      • Working With Dates
      • Working With Text
      • Working With Files
      • Debugging Applications
    • C Sharp Intermediate
      • Classes
      • Association Between Classes
      • Inheritance
      • Polymorphism
      • Interfaces
  • Java
    • Inheritance Data Structures Java
      • Inheritance Polymorphism Using Overriding And Access Modifiers
      • Abstract Classes And Debugging
      • File I O And Exceptions
      • Collections Maps And Regular Expressions
    • Intro To Java
      • Introduction To Java Classes And Eclipse
      • Unit Testing Arrays And Array Lists
      • Static Variables Methods And Polymorphism Using Overloading
  • Javascript
    • Algorithms Data Structures
      • Big O Notation
      • Analyzing Performance Of Arrays And Objects
      • Problem Solving Approach
      • Problem Solving Patterns
      • Recursion
      • Searching Algorithms
      • Bubble Selection And Insertion Sort
      • Merge Sort
      • Quick Sort
      • Radix Sort
      • Data Structures Introduction
      • Singly Linked Lists
      • Doubly Linked Lists
      • Stacks And Queues
      • Binary Search Trees
      • Tree Traversal
      • Binary Heaps
    • Complete Nodejs
      • Understanding Node.js
      • REST AP Is And Mongoose
      • API Authentication And Security
      • Node.js Module System
      • File System And Command Line Args
      • Debugging Node.js
      • Asynchronous Node.js
      • Web Servers
      • Accessing API From Browser
      • Application Deployment
      • Mongo DB And Promises
    • Complete React Native
      • Working With Content
      • Building Lists
      • Navigating Users Between Screens
      • State Management
      • Handling Screen Layout
      • Setting Up An App
      • More On Navigation
      • Advanced Statement Management With Context
      • Building A Custom Express API
      • In App Authentication
    • Epic React
      • React Fundamentals
      • React Hooks
      • Advanced React Hooks
      • Advanced React Patterns
      • React Performance
    • Fireship Firestore
      • Firestore Queries And Data Modeling Course
      • Model Relational Data In Firestore No SQL
    • Functional Light Javascript
      • Intro
      • Function Purity
      • Argument Adapters
      • Point Free
      • Closure
      • Composition
      • Immutability
      • Recursion
      • List Operations
      • Transduction
      • Data Structure Operations
      • Async
    • Js Weird Parts
      • Execution Contexts And Lexical Environments
      • Types And Operators
      • Objects And Functions
      • Object Oriented Java Script And Prototypal Inheritance
      • Defining Objects
    • Mastering Chrome Dev Tools
      • Introduction
      • Editing
      • Debugging
      • Networking
      • Auditing
      • Node.js Profiling
      • Performance Monitoring
      • Image Performance
      • Memory
    • React Complete Guide
      • What Is React
      • React Basics
      • Rendering Lists And Conditionals
      • Styling React Components
      • Debugging React Apps
      • Component Deep Dive
      • Building A React App
      • Reaching Out To The Web
      • Routing
    • React Testing
      • Intro To Jest Enzyme And TDD
      • Basic Testing
      • Redux Testing
      • Redux Thunk Testing
    • Serverless Bootcamp
      • Introduction
      • Auction Service Setup
      • Auction Service CRUD Operations
      • Auction Service Processing Auctions
    • Testing Javascript
      • Fundamentals Of Testing
      • Static Analysis Testing
      • Mocking Fundamentals
      • Configuring Jest
      • Test React Components With Jest And React Testing Library
    • Typescript Developers Guide
      • Getting Started With Type Script
      • What Is A Type System
      • Type Annotations In Action
      • Annotations With Functions And Objects
      • Mastering Typed Arrays
      • Tuples In Type Script
      • The All Important Interface
      • Building Functionality With Classes
    • Web Performance With Webpack
      • Intro
      • Code Splitting
      • Module Methods Magic Comments
  • Other
    • Algo Expert
      • Defining Data Structures And Complexity Analysis
      • Memory
      • Big O Notation
      • Logarithm
      • Arrays
      • Linked Lists
      • Hash Tables
      • Stacks And Queues
      • Strings
      • Graphs
      • Trees
    • Aws Solutions Architect
      • AWS Fundamentals IAM EC 2
    • Fundamentals Math
      • Numbers And Negative Numbers
      • Factors And Multiples
      • Fractions
    • Mysql Bootcamp
      • Overview And Installation
      • Creating Databases And Tables
      • Inserting Data
      • CRUD Commands
      • The World Of String Functions
      • Refining Our Selections
      • The Magic Of Aggregate Functions
    • Random Notes
      • Understanding React Hooks
  • Python
    • Data Analysis Using Python
      • Loading Querying And Filtering Data Using The Csv Module
      • Loading Querying Joining And Filtering Data Using Pandas
      • Summarizing And Visualizing Data
    • Intro To Python
      • Course Introduction Intro To Programming And The Python Language Variables Conditionals Jupyter Notebook And IDLE
      • Intro To Lists Loops And Functions
      • More With Lists Strings Tuples Sets And Py Charm
      • Dictionaries And Files
Powered by GitBook
On this page
  • Routing Props
  • Link Component
  • Navigating programmatically
  • Route Parameters
  • Using Switch
  • Nested Routes
  1. Javascript
  2. React Complete Guide

Routing

Routing Props

When react-router renders a component, it passes routing-related props: history, location, and match.

<Route path='/blog' component={Blog} />

// In Blog.js...
const Blog = props => {
  console.log(props) // Includes routing-related props

  return (
    <div>I'm a blog</div>
  )
}

Pro tip: Another way to gain access to routing-related props is to use the higher-order component withRouter.

import { withRouter } from 'react-router-dom'

// ...

export default withRouter(Component)

Link Component

The Link component basically renders an anchor component and prevents the default behaviour, re-rendering the DOM instead of navigating to the new link and losing state. Here's some useful tips...

You can pass an object instead of a string:

<Link to={{
  pathname: '/login',
  hash: '#start',
  search: '?new-user=true'
}}>
  Log In
</Link>

By default, the path you provide is absolute, appending it to the root domain. To make it relative, just use routing-related props:

// In Blog.js
<Link to={{
  pathname: this.props.match.url + '/login' // becomes '/blog/login'
}}>
  Log into Blog
</Link>

If you want to add styling to your active links, use NavLink instead:

<NavLink
  to='/login'
  exact // important!
  activeClassName='activeLink' // defaults to 'active'
  activeStyle={{
    color: 'red'
  }}
>
  Log In
</NavLink>

Navigating programmatically

Sometimes, instead of using Link to immediately navigate to a URL, we want to first run some code and then navigate to the URL.

In this case, we can programmatically navigate to a URL using the history prop provided:

<Component
  onClick={() => {
    // Do stuff first and then...
    this.props.history.push({ pathname: '/new-url' })
  }} />

Note: Recall how browser history is like a linked list. By pushing to the end of the list, we're navigating to a new page by adding it to history.

Route Parameters

Suppose we want to display a blog post with the url https://blog.com/my-blog-post, using my-blog-post as the slug used to query the blog post contents.

Here's how we can access the parameter:

<Route path='/:slug' exact component={Post} />

// In Post.js...
async componentDidMount() {
  const postData = await getPost(this.props.match.params.slug)
  // ...
}

By marking our :slug value as a dynamic value, we have access to slug as a routing-related prop.

Using Switch

When implementing multiple Route components, it's common to accidentally render more components than you want.

The Switch component helps with this. Like the switch statement, it renders the first Route that matches the path visited:

<Switch>
  <Route path='/' exact component={Home} />
  <Route path='/blog' component={Blog} >
</Switch>

Nested Routes

It's possible to have a Route component inside another Route component. However, it's important to understand that the parent Route needs to remain rendered when you navigate to the child Route.

The below example will not work because when you navigate to /:slug, Blog will unmount because the route doesn't match /blog. And because the child Route is part of Blog, it will also unmount.

// Parent: App.js
<Route path='/blog' component={Blog} />

// Child: Blog.js
<Route path='/:slug' component={Post} />

To solve this, it's better to utilize a relative path (as mentioned earlier). The below example will work because this.props.match.url will include /blog in the URL.

// Parent: App.js
<Route path='/blog' component={Blog} />

// Child: Blog.js
<Route path={this.props.match.url + '/:slug'} component={Post} />
PreviousReaching Out To The WebNextReact Testing

Last updated 3 years ago