title: Get query parameters from react-router-dom into a functional component?
body: <p>I have a router file to which I am passing query parameters to a functional component. I am using react-router-dom how can I get the query parameters in a functional component?</p>
  
  <p>The line in question which sends parameters is </p>
  
  <pre><code>&lt;Route path="/reports/daily-sales-single/:date_from" component={DailySalesSingle} /&gt;
  </code></pre>
  
  <p>Here I am sending a date_from parameter. I have seen various ways but none of them see conclusive in how to do this or seem out of date. Also every tutorial seems to be people using class components.</p>
  
  <p>Router file:</p>
  
  <pre><code>    import * as React from 'react';
  import {
      BrowserRouter as Router,
      Route,
      Switch,
  } from 'react-router-dom';
  import { asyncComponent } from '@hoc/index';
  import { useSpring, useTransition, animated } from 'react-spring';
  import useRouter from '@hooks/useRouter';
  
  import Error from '@containers/Error/index';
  
  const Home = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/home" */ '@containers/home').then(
      module =&gt; module.default,
  ));
  
  const RatesOverview = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/ratesoverview" */ '@containers/RatesOverview').then(
      module =&gt; module.default,
  ));
  
  const CreateRate = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/createrates" */ '@containers/CreateRates').then(
       module =&gt; module.default,
  ));
  
  const CopyRate = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/createrates" */ '@containers/CreateRates/copyRate').then(
       module =&gt; module.default,
  ));
  
  const RateHurdleOverview = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/hurdleOverview" */ '@containers/RateHurdleOverview').then(
    module =&gt; module.default,
  ));
  
  const DailySalesSingle = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/dailysalessingle" */ '@containers/Reports/DailySalesSingle').then(
      module =&gt; module.default,
  ));
  
  const DailySalesGroup = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/dailysalesgroup" */ '@containers/Reports/DailySalesGroup').then(
      module =&gt; module.default,
  ));
  
  const WeeklySalesSingle = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/weeklysalessingle" */ '@containers/Reports/WeeklySalesSingle').then(
      module =&gt; module.default,
  ));
  
  const WeeklySalesGroup = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/weeklysalesgroup" */ '@containers/Reports/WeeklySalesGroup').then(
      module =&gt; module.default,
  ));
  
  const Settings = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/settings" */ '@containers/Settings').then(
      module =&gt; module.default,
  ));
  
  const CreateRateHurdle = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/hurdlecreaterate" */ '@components/Forms/CreateRateHurdle').then(
      module =&gt; module.default,
  ));
  
  const RatesGrid = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/ratesgrid" */ '@containers/RatesGrid').then(
      module =&gt; module.default,
  ));
  
  const GroupDasboard = asyncComponent(() =&gt; import(/* webpackChunkName: "js/chunks/groupdashboard" */ '@containers/Group/Dashboard').then(
    module =&gt; module.default,
  ));
  
  const Routes = () =&gt; {
      /* eslint-disable  no-shadow */
      const { location } = useRouter();
      const transitions = useTransition(location, location =&gt; location.pathname, {
          from: {
              opacity: 0,
              position: 'absolute',
              width: '100%',
              transform: 'translate3d(-100%, 0, 0)',
          },
          enter: {
              opacity: 1,
              transform: 'translate3d(0, 0, 0,)',
          },
          leave: { opacity: 0, transform: 'translate3d(150%, 0, 0)' },
      });
      /* eslint-enable no-shadow */
      return transitions.map(({ item, key, props }) =&gt; (
          &lt;&gt;
          &lt;div className="app-page"&gt;
            &lt;animated.div className="app-content" key={key} style={props}&gt;
                  &lt;Error /&gt;
                  &lt;Switch location={item}&gt;
                      &lt;Route exact path="/" component={GroupDasboard} /&gt;
                      &lt;Route path="/rates/overview" component={RatesOverview} /&gt;
                      &lt;Route path="/rates/create" component={CreateRate} /&gt;
                      &lt;Route path="/rates/grid" component={RatesGrid} /&gt;
                      &lt;Route path="/rates/copy/:rate_id" component={CopyRate} /&gt;
                      &lt;Route path="/rates/hurdle/create" component={CreateRateHurdle} /&gt;
                      &lt;Route path="/rates/hurdle" component={RateHurdleOverview} /&gt;
                      &lt;Route path="/reports/daily-sales-single/:date_from" component={DailySalesSingle} /&gt;
                      &lt;Route path="/reports/daily-sales-group" component={DailySalesGroup} /&gt;
                      &lt;Route path="/group/dashboard" component={GroupDasboard} /&gt;
                      &lt;Route path="/reports/weekly-sales-single" component={WeeklySalesSingle} /&gt;
                      &lt;Route path="/reports/weekly-sales-group" component={WeeklySalesGroup} /&gt;
                      { /* &lt;Route path="/settings" component={Settings} /&gt; */}
                  &lt;/Switch&gt;
            &lt;/animated.div&gt;
          &lt;/div&gt;
          &lt;/&gt;
      ));
  };
  
  export default Routes;
  </code></pre>
  
  <p>Functional Component:</p>
  
  <pre><code>    import * as React from 'react';
  import { connect } from 'react-redux';
  import * as actions from '@actions/index';
  
  import { QuickSearchMenu, WeeklyQuickSearchMenu } from '@constants/DateLists';
  import { SearchBarDatesSchema } from '@constants/Yup/SearchBarDatesSchema.ts';
  
  import { ToggleWithLabel } from '@components/inputs/index';
  import PageHeader from '@components/Header/PageHeader';
  
  import {
    Jumbotron,
    Container,
    Row,
  } from 'react-bootstrap';
  
  import {
    Formik,
    Form,
    Field,
  } from 'formik';
  
  import { log } from 'util';
  
  import Title from './Title';
  import SearchBy from './SearchBy';
  import QuickSearch from './QuickSearch';
  import Dates from './Dates';
  import Properties from './Properties';
  import DepartmentToggle from './DepartmentToggle';
  import DepartmentTitle from './DepartmentTitle';
  import RunReport from './RunReport';
  import AdvSearch from './AdvSearch';
  import AdvSearchToggle from './AdvSearchToggle';
  import Options from './Options';
  
  interface StateProps {
    isModalOpen: boolean;
    isSidebarOpen: boolean;
  }
  
  interface InitialProps {
    page: any;
    title: any;
    subTitle: string;
    dataLocal: any;
    type: string;
  }
  
  interface DispatchProps {
    getAllDepartments: (payload: any) =&gt; void;
    getAllPaymentMethods: (payload: any) =&gt; void;
  }
  
  type Props = InitialProps &amp; StateProps &amp; DispatchProps;
  
  function mapDispatchToProps(dispatch: React.Dispatch&lt;any&gt;): DispatchProps {
    return {
      getAllDepartments: payload =&gt; dispatch(actions.Reports.getAllDepartments(payload)),
      getAllPaymentMethods: payload =&gt; dispatch(actions.Reports.getAllPaymentMethods(payload)),
    };
  }
  
  const Header = ({
    page,
    title,
    subTitle,
    dataLocal,
    getAllDepartments,
    getAllPaymentMethods,
    type,
   }: Props) =&gt; {
    const [department, setDepartment] = React.useState({ status: true });
    const [advSearch, setAdvSearch] = React.useState({ status: false });
    const [quickSearchDates, setQuickSearchDates] = React.useState({
      dateName: null,
      fromDate: null,
      toDate: null,
    });
    const [apiDates, setApiDates] = React.useState({
      fromDate: null,
      toDate: null,
    });
  
    const [netOrGross, setNetOrGross] = React.useState(true);
  
    const updateQuickSearchDates = () =&gt; {
      if (apiDates.fromDate === null &amp;&amp; apiDates.toDate === null) {
        const today = new Date();
        setQuickSearchDates({
          dateName: 'Today',
          fromDate: today,
          toDate: today,
        });
      }
    };
  
    const getQuickSearchMenu = () =&gt; ((
    page === 'weekly-sales-single'
    || page === 'weekly-sales-group')
    ? WeeklyQuickSearchMenu
    : QuickSearchMenu);
  
    const disableComponent = () =&gt; ((
    page === 'weekly-sales-single'
    || page === 'weekly-sales-group')
    // eslint-disable-next-line
    ? true
    : false);
  
    const onChange = (e: MouseEvent | KeyboardEvent) =&gt; {
      setNetOrGross(e.target.value);
    };
  
    return (
      &lt;div className="daily-sales-header"&gt;
      &lt;PageHeader title={title} helpPage="help"&gt;
          &lt;Container fluid&gt;
            &lt;Formik
              validateOnChange
              initialValues={{}}
              validationSchema={SearchBarDatesSchema}
              onSubmit={(values, { setSubmitting }) =&gt; {
                updateQuickSearchDates();
                getAllPaymentMethods({
                  type,
                  apiDates,
                });
                getAllDepartments({
                  type,
                  department,
                  apiDates,
                });
                setSubmitting(false);
              }}
            &gt;
                {({
                  isSubmitting,
                  handleSubmit,
                }) =&gt; (
                &lt;Form onSubmit={handleSubmit}&gt;
                  &lt;Row&gt;
                    {/* { page === 'daily-sale-single' &amp;&amp; (
                    &lt;SearchBy
                      colClass="search-by-col"
                      buttonId="search-by-button"
                      buttonLabel="Search by"
                    /&gt;
                    )} */}
                    &lt;QuickSearch
                      buttonLabel="Quick Search"
                      eleClass="quick-search"
                      eleIdBtn="quick-search-button"
                      quickSearchMenu={getQuickSearchMenu()}
                      setQuickSearchDates={setQuickSearchDates}
                      getQuickSearchDates={quickSearchDates}
                      disable={disableComponent()}
                    /&gt;
                    &lt;Field
                      fromClass="from-date"
                      fromLabel="From"
                      toClass="to-date"
                      toLabel="To"
                      setQuickSearchDates={quickSearchDates}
                      setApiDates={setApiDates}
                      component={Dates}
                      disable={disableComponent()}
                    /&gt;
                    { page === 'daily-sale-groups' &amp;&amp; (
                    &lt;Properties
                      colClass="search-by-col"
                      buttonId="search-by-button"
                      buttonLabel="Properties"
                    /&gt;
                    )}
                    { (page === 'daily-sale-single'
                        || page === 'weekly-sales-single'
                        || page === 'weekly-sales-group') &amp;&amp; (
                    &lt;DepartmentToggle
                      buttonOneLabel="Department"
                      buttonTwoLabel="Sub-Department"
                      variantSelected="primary"
                      variantUnSelected="outline-primary"
                      setDepartment={setDepartment}
                      status={department.status}
                      isSubmitting={isSubmitting}
                      disable={disableComponent()}
                    /&gt;
                    )}
                    &lt;RunReport
                      buttonLabel="Run Report"
                      isSubmitting={isSubmitting}
                      departmentToggle={department.status}
                      disable={disableComponent()}
                    /&gt;
                  &lt;/Row&gt;
                  &lt;AdvSearch
                    advSearchToggle={advSearch.status}
                  /&gt;
                  &lt;Row&gt;
                    &lt;AdvSearchToggle
                      buttonClass="adv-search-btn pull-right"
                      buttonLabel="Advanced Search"
                      setAdvSearch={setAdvSearch}
                      status={advSearch.status}
                    /&gt;
                  &lt;/Row&gt;
                &lt;/Form&gt;
              )}
            &lt;/Formik&gt;
          &lt;/Container&gt;
        &lt;Row&gt;
          &lt;DepartmentTitle
            title="Department"
            departmentToggle={department.status}
            departmentClass="display-title"
          /&gt;
          &lt;div className="col-md-auto"&gt;
          { (page === 'weekly-sales-single'
            || page === 'weekly-sales-group') &amp;&amp; (
          &lt;div className="col-md-auto"&gt;
            &lt;ToggleWithLabel
              label="Net / Gross"
              field={{
                onChange,
                value: netOrGross,
                name: 'net_or_gross',
              }}
            /&gt;
          &lt;/div&gt;
          )}
          &lt;/div&gt;
          &lt;Options
            data={dataLocal}
          /&gt;
        &lt;/Row&gt;
      &lt;/PageHeader&gt;
      &lt;/div&gt;
    );
  };
  
  export default connect(null, mapDispatchToProps)(Header);
  </code></pre>