0

I am using react-router-dom and according to docs it says for url pattern https:\\example.com\user\:id\:gender we can use useParams() hook to read the patters like

import {useParams, Route} from react-router;

<Route exact path="/user/:id/:gender" component={User}/>

const user=(props)=>{
const params = useParams()
}

//params = {id:'1',gender:'f'}; output for url pattern >>> https:\\example.com\user\1\f 

But in my case, I have two requirement

  1. gender field is sometime required and some time not, then what changes needed in the Router?
  2. How to read url pattern https://example.com/user?id=1&gender=f , because in this patter If I interchange the order then no effect will be on parameter object.

2 Answers 2

0

You can destructure the params as follows and use them anywhere

const { id , gender } = useParams();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for reply, I need something else, there is difference between two pattern example.com/user?id=1&gender=f and example.com\user\1\f how to read first one? @VH Aberyvickrama
0

You need to use query params if you are trying to append optional data in URL as you discussed above.

you can simply use "useLocation()" hook provided by react-router-dom library to extract query params from any url.

// https://example.com/user?id=1&gender=f
import React from "react";

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

function QueryParamsDemo() {
  let query = useLocation().search;
  let getParams = () => console.log(query); // output will be {id:1,gender:"f"}
  return (
    <div>
      <button onClick={() => getParams()}>Get Param</button>
    </div>
  );
}

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.