Chapter 4: Routing with React Router

  1. We have the following Route that shows a list of customers:
<Route path="/customers" component={CustomersPage} />

Will the CustomersPage component render when the page is "/customers"?
Yes

  1. Will the CustomersPage component render when the page is "/customers/24322"?
    Yes
  2. We only want the CustomersPage component to render when the path is "/customers". How can we change the attributes on Route to achieve this?

We can use the exact attribute:

<Route exact={true} path="/customers" component={CustomersPage} />
  1. What would be the Route that could handle the path "/customers/24322"? It should put "24322" in a route parameter called customerId:
<Route exact={true} path="/customers/:customerId" component={CustomerPage} />
  1. We can then use RouteComponentProps as the CustomerPage props type and get access to customerId via props.match.params.customerId.

How can we catch paths that don't exist so that we can inform the user?

Make sure all the Route components are wrapped in a Switch component. We can then add a Route to a component that renders a not found message to the user as the last Route in Switch:

<Switch>
<Route path="/customers/:customerId" component={CustomerPage} />
<Route exact={true} path="/customers" component={CustomersPage} />
<Route component={NotFoundPage} />
</Switch>
  1. How would we implement a search query parameter in CustomersPage? So, "/customers/?search=Cool Company" would show customers the name Cool Company.

First we need the props type to be RouteComponentProps in our class:

import { RouteComponentProps } from "react-router-dom";

class CustomersPage extends React.Component<RouteComponentProps, IState> { ... }

We can the use URLSearchParams to get the search query parameter and do the search in the componentDidMount life cycle method:

public componentDidMount() {
const searchParams = new URLSearchParams(props.location.search);
const search = searchParams.get("search") || "";

const products = await ... // make web service call to do search

this.setState({ products });
}
  1. After a while we decide to change the "customer" paths to "clients". How can we implement this so that users can still use the existing "customer" paths but have the paths automatically redirect to the new "client" paths.

We can use the Redirect component to redirect the old paths to the new paths:

<Switch>
<Route path="/clients/:customerId" component={CustomerPage} />
<Route exact={true} path="/clients" component={CustomersPage} />

<Redirect from="/customers/:customerId" to="/clients/:customerId" />
<Redirect exact={true} from="/customers" to="/clients" />

<Route component={NotFoundPage} />
</Switch>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.219.166