How can we pass parameter with this.props.history.push(\'/page\')
in React-Router v4?
.then(response => {
var r = this;
if (re
Extending the solution (suggested by Shubham Khatri) for use with React hooks (16.8 onwards):
package.json (always worth updating to latest packages)
{
...
"react": "^16.12.0",
"react-router-dom": "^5.1.2",
...
}
Passing parameters with history push:
import { useHistory } from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: { detail: 'some_value' }
});
};
};
export default FirstPage;
Accessing the passed parameter using useLocation from 'react-router-dom':
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
React TypeScript with Hooks
From a Class
this.history.push({
pathname: "/unauthorized",
state: { message: "Hello" },
});
UnAuthorized Functional Component
interface IState {
message?: string;
}
export default function UnAuthorized() {
const location = useLocation();
const message = (location.state as IState).message;
return (
<div className="jumbotron">
<h6>{message}</h6>
</div>
);
}
Add on info to get query parameters.
const queryParams = new URLSearchParams(this.props.location.search);
console.log('assuming query param is id', queryParams.get('id');
For more info about URLSearchParams check this link URLSearchParams
I created a custom useQuery hook
import { useLocation } from "react-router-dom";
const useQuery = (): URLSearchParams => {
return new URLSearchParams(useLocation().search)
}
export default useQuery
Use it as
const query = useQuery();
const id = query.get("id") as string
Send it as so
history.push({
pathname: "/template",
search: `id=${values.id}`,
});