I am new to react. I am trying to pass the parameters to another component using navigate.page is redirected successfully but I am facing error while reading param values.
App.js:
<Router>
<Routes>
<Route path="/test" element ={<testLayout/>}
<Route path="/valid" element ={<validation/>}
</Routes>
</Router>
root page:
class testLayout extends Component {
render(){
<div>
<Selection/>
</div>
}
}
export default testLayout;
Firstpage:
export default function Selection(){
const navigate= useNavigate();
const handleclick = (params) => {
let id= params.id;
let path = '/valid';
navigate(path,{docId:id});
}
return(
<DataGrid onCellClick={handleclick} />
);
}
Valid page:
Import React, {Component} from "react";
class validation extends Component
{
render(){
const {navigation } = this.props;
let rs= navigation.getParam('docId','default value')
return(
<div>
<h1> hi {rs}<h1>
</div>
);
}
}
export default validation;
I am getting bellow error Can't read properties of undefined (reading 'getParam')
I know somewhere I am missing something. Can anyone help me to fix this.
Thanks
in order to get props passed with navigate (useNavigate) u need the useLocation hook which cannot be used inside a class component so you can use a wrapper like you did with the selection component and use it within to extract the props it would look like this
class Validation extends Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props);
return (
<div>
<div>im Rendered </div>
<Wrapper />
</div>
);
}
}
export default Validation;
function Wrapper() {
const {
state: { docId }
} = useLocation();
return <div>im Rendered {docId}</div>;
}
also when passing i changed this line navigate(path, { state: { docId: id } });
here a codesandbox