-1

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??

2
  • Are you using react-router-dom V6? Commented Jul 30, 2022 at 10:54
  • yes @GodWin .... Commented Jul 30, 2022 at 10:59

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.