I am trying to pass in a path variable, userId, as a prop to a React component rendered by React Router:
Profile.js
export const Profile = (props) => {
//array of compatible users fetched for a user.
const [userProfileInformation, setUserProfileInformation] = useState([]);
const [isLoading, setLoading] = useState(true);
useEffect(() => {
getUserProfileInformation().then(() => {
setLoading(false);
});
}, []);
const getUserProfileInformation = async () => {
//Currently hardcoded value until authorisation implemented.
const userId = this.props.match.params.id;
const response = await UserService.getUserProfileInformation(userId)
.then(response => response.json())
.then(data => {
setUserProfileInformation(data);
});
}
if (isLoading) {
return (
<div id="loading">
<h2>Loading...</h2>
</div>
)
}
return (
<div>
<div className="profileCard">
<h2>{userProfileInformation.email}</h2>
</div>
</div>
)
}
The error occurs because of the 'userId = props.match.params.id' code.
App.js:
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="/profile/:userId" element={<Profile />} />
</Routes>
</BrowserRouter>
);
Dashboard.js:
export const Dashboard = () => {
return(
<div>
<h2>Dashboard</h2>
<Button color="link"><Link to={`/profile/1`}>Profile</Link></Button>
</div>
);
}
The above temporarily uses a hardcoded value for the link, 1.
Edit:
Tried with const userId = props.match.params.id;
and const userId = this.props.match.params.id
and const userId = props.match.params.userId;
and const userId = this.props.match.params.userId;
All give same result as before.
Thanks