The full url is /login?redirect=shipping. I want to split it into two parts like this - /login?redirect and shipping. I need the second part of the url. that is shipping How can I do this in reactjs??
1 Answer
You can use useSearchParams from react-router-dom v6.
You can also use URLSearchParams (Provided by Browsers)
In your case it would be as follows:
import React from "react";
import { useSearchParams, useLocation } from "react-router-dom";
export const App = () => {
const [searchParams, setSearchParams] = useSearchParams();
const { search } = useLocation();
console.log(searchParams.get("redirect"));
// if it's more than 1 value for redirect i.e. redirect=shipping&redirect=shipped
console.log(searchParams.getAll("redirect")); // will return array of value
// you can use URLSearchParams also by passing search query
console.log(new URLSearchParams(search).get("redirect"));
// URLSearchParams is provided by Browser.
return <div>Search Param</div>;
};
PS: Follow useSearchParams approach if using react and specifically react-router-dom V6 or else go for URLSearchParams
react-router-domV6?