Reputation: 41
I want to pass props into a function from the route, my code currently looks like this
Route
<Route path="/person" render={(params) => <ProductDetails {...params} />} />
Code
function ProductDetails(props) {
return (
<div className="section has-text-centered mt-4">
console.log(props)
<h1>Hello</h1>
</div>
);
};
export default ProductDetails;
What am I missing here, please help.
Upvotes: 4
Views: 7425
Reputation: 51
You can pass function with props in React Router DOM V6 in this way:
<Route path="/person" element={<ProductDetails render={(params) => ({ ...params })} />} />
And you can pass more props as names outside of render function.
Example:
<Route path="/person" element={<ProductDetails render={(params) => ({ ...params })} user={user} />} />
Upvotes: 0
Reputation: 202741
In react-router-dom
v6 you pass props to the routed component directly since they are passed as a ReactElement
(a.k.a. JSX).
Example:
<Route path="person" element={<ProductDetails /* pass props here */ />} />
Based on your example snippet though, it sounds like your question it more specifically about passing the "route props" to a component. In RRDv6 there are no longer any route props, i.e. no history
, location
, and match
props. Use the React hooks to access these: useNavigate
for navigation, useLocation
for location
, and useMatch
for match
and useParams
specifically for the route params.
import { useNavigate, useLocation, useParams } from 'react-router-dom';
function ProductDetails(props) {
const navigate = useNavigate();
const location = useLocation();
const match = useMatch();
useEffect(() => {
console.log(props);
}, [props]);
return (
<div className="section has-text-centered mt-4">
<h1>Hello</h1>
</div>
);
};
export default ProductDetails;
Upvotes: 1