I have the following Router:
// index.js
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import history from "./history";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Router history={history}>
<Routes>
<Route path='/Page1' element={<Page1/>} />
<Route path='/Page2' element={<Page2/>} />
</Routes>
</Router>
);
// history.js
import { createBrowserHistory } from 'history'
export default createBrowserHistory();
I'm trying to pass data from Page1 to Page2 using <Link>
from React-Router V6. To be more explicit, I'm doing this because Page1 contains a list of participants, each with an edit button. When the edit button is clicked, Page2 opens. Page2 is a form containing the data of the participant you want to edit. Here is a picture so you can visualize it.
Page1 is a class component while Page2 is a functional component with Hooks so that I can call useLocation(). After I retrieve the data from Page1, I want to pre-complete the form. Page2 is a functional component because in React-Router V6, you can only do this using useLocation() hook, as explained here
A) Page1 where I'm passing the data to Page2
//Page1
class CandidatesList extends Component {
// ...
listOfParticipants = this.state.listOfParticipants.map((participant) => {
return(
<Link to="/Page2" state={{participant: participant}} className="btn btn-primary">Edit Participant</Link>
// This is the edit button that opens Page2 while passing the data
)
}
B) Page2 where I'm retrieving the data from Page1
///////////// Page2
// ...
function Page2() {
const { state } = useLocation()
console.log(state.participant) //
useEffect(() => {
/// ...
}
}
However, it seems that the data is never received in Page2 and I get the following error (when I try to console.log()
it)
Uncaught TypeError: Cannot read properties of null (reading 'participant')
What am I doing wrong and why is the data not getting passed?