Simmi George
Simmi George

Reputation: 225

Correct way to set queryString in react-router-dom?

My application uses angularJS, so I'm migrating it to React. I'm navigating to a route: /index like this $urlServiceProvider.rules.otherwise('/index').Note that I'm using angularJS's urlServiceProvider to navigate to /index which has $stateProvider set like this :

$stateProvider.state('index', {
     component: AppController,
     url: '/index',
     template: `<div id="application"></div>`
})

// AppController.jsx

import * as ReactDOM from 'react-dom'
import * as React from 'react'
import App from './App'
export class AppController implements ng.IComponentController {
  constructor() {}

  $onInit(): void {
    ReactDOM.render(<App />, document.getElementById('application'))
  }
}

<App /> component is a component in react which has routes defined for every page.

Now, this works fine but what If I want to set queryString params, which I did it like this: /index?redirect=true. Now, inside <App /> component if I log the value like:

// App

const { redirect } = useLocation()
console.log('Redirect value is ', redirect) // Expecting true here

I get nothing printed in console. Am I doing it correct here?

Upvotes: 1

Views: 175

Answers (1)

Drew Reese
Drew Reese

Reputation: 202801

If using react-router-dom@6 you can use the useSearchParams hook.

Example:

import { useSearchParams } from 'react-router-dom';

...

const [searchParams] = useSearchParams();
const redirect = searchParams.get("redirect");

If using react-router-dom@5 you will need to use the useLocation hook and access the location.search value and instantiate your own URLSearchParams object.

Example:

import { useLocation } from 'react-router-dom';

...

const { search } = useLocation();
const searchParams = new URLSearchParams(search);
const redirect = searchParams.get("redirect");

In RRDv5 you can abstract a custom hook to do this for you:

const useQuery = () => {
  const { search } = useLocation();
  return React.useMemo(() => new URLSearchParams(search), [search]);
}

Upvotes: 2

Related Questions