Using query parameters

A query parameter is part of the URL that allows additional parameters to be passed into a path. For example, /search?criteria=typescript has a query parameter called criteria with a value of typescript.

In this section, we are going to implement a query parameter on the search page called criteria, which will drive the search. We'll implement the search page along the way. Let's carry out these steps to do this:

  1. We are going to start in QuestionsData.ts by creating a function to simulate a search via a web request:
export const searchQuestions = async (
criteria: string,
): Promise<QuestionData[]> => {
await wait(500);
return questions.filter(
q =>
q.title.toLowerCase().indexOf(criteria.toLowerCase()) >=
0 ||
q.content.toLowerCase().indexOf(criteria.toLowerCase()) >=
0,
);
};

So, the function uses the array filter method and matches the criteria to any part of the question title or content.

  1. Let's import this function along with the other items we need into SearchPage.tsx. We can also remove the React namespace from the existing import statement:
import { FC, useState, useEffect } from 'react';
import { RouteComponentProps } from 'react-router-dom';
import { Page } from './Page';
import { QuestionList } from './QuestionList';
import { searchQuestions, QuestionData } from './QuestionsData';
/** @jsx jsx */
import { css, jsx } from '@emotion/core';
  1. Let's add RouteComponentProps as the props type for the SearchPage component and destructure the location object. We'll also change the component so that it uses an explicit return statement:
export const SearchPage: FC<RouteComponentProps> = ({
location,
}) => {
return <Page title="Search Results" />;
};

  1. We are going to create some state to hold the matched questions in the search:
export const SearchPage: FC<RouteComponentProps> = ({
location,
}) => {
const [questions, setQuestions] = useState<QuestionData[]>([]);
return <Page title="Search Results" />;
};
  1. Next, we are going to get the criteria query parameter from the browser: 
export const SearchPage: FC<RouteComponentProps> = ({ location }) => {
const [questions, setQuestions] = useState<QuestionData[]>([]);

const searchParams = new URLSearchParams(location.search);
const search = searchParams.get('criteria') || '';

return <Page title="Search Results" />;
};
React Router gives us access to all the query parameters in a search string inside the location object.

The search string from React Router for the /search?criteria=type path is ?criteria=type. So, we need to parse this string in order to get the criteria value. We use the native URLSearchParams JavaScript function to do this.

  1. We are going to invoke the search when the component first renders and when the search variable changes using the useEffect hook:
const searchParams = new URLSearchParams(props.location.search);
const search = searchParams.get('criteria') || '';

useEffect(() => {
const doSearch = async (criteria: string) => {
const foundResults = await searchQuestions(criteria);
setQuestions(foundResults);
};

doSearch(search);
}, [search]);
  1. We are going to render the search criteria under the page title:
<Page title="Search Results">
{search && (
<p
css={css`
font-size: 16px;
font-style: italic;
margin-top: 0px;
`}
>
for "{search}"
</p>
)}
</Page>
  1. The last task is to use the QuestionList component to render the questions that are returned from the search:
<Page title="Search Results">
{search && (
<p ... >
for "{search}"
</p>
)}
<QuestionList data={questions} />
</Page>

Our QuestionList component is now used in both the home and search pages with different data sources. The reusability of this component has been made possible because we have followed the container pattern we briefly mentioned in Chapter 3, Getting Started with React and TypeScript.

  1. In the running app, enter /search?criteria=type in the browser. The search will be invoked and the results will be rendered as we would expect:

So, we need to do a bit of work beyond what React Router provides in order to handle query parameters, but this is still fairly straightforward with the help of URLSearchParams.

In Chapter 5, Working with Forms, we'll wire up the search box in the header to our search form.

In the next section, we'll learn how we can load components on demand.

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

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