2

I want to know How can I get data from query string using route in reactJs. Can anyone please help me to get the answer?

export default function ParamsExample() {
    return (
        <Router>
            <div>
                <ul>
                    <li>
                        <Link to="/">Home</Link>
                    </li>
                    <li>
                        <Link to="/about">About</Link>
                    </li>
                </ul>
            </div>
        </Router>
    );
}

function Child() {
    let {query} = window.location.href;

    return (
        <div>
            <h3>query: {query}</h3>
        </div>
    );
}

2 Answers 2

5

Please check the below example. hope it helps you.

import React from "react";
import {
    BrowserRouter as Router,
    Switch,
    Route,
    Link,
    useParams
} from "react-router-dom";

export default function ParamsExample() {
    return (
        <Router>
            <div>
                <h2>Accounts</h2>

                <ul>
                    <li>
                        <Link to="/netflix">Netflix</Link>
                    </li>
                    <li>
                        <Link to="/zillow-group">Zillow Group</Link>
                    </li>
                    <li>
                        <Link to="/yahoo">Yahoo</Link>
                    </li>
                    <li>
                        <Link to="/modus-create">Modus Create</Link>
                    </li>
                </ul>

                <Switch>
                    <Route path="/:id" children={<Child/>}/>
                </Switch>
            </div>
        </Router>
    );
}

function Child() {
    let {id} = useParams();

    return (
        <div>
            <h3>ID: {id}</h3>
        </div>
    );
}

Source

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

Comments

1

Parameters can be obtained using useParams() while query string can be parsed using browser URLSearchParams. const query_key = new URLSearchParams(this.props.location.search).get("query_key")

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.