GF7ER - فيلو
GF7ER - فيلو

Reputation: 41

How To Pass Props To Function Component use react-router-dom v6

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

Answers (2)

Ikram Ul Haq
Ikram Ul Haq

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

Drew Reese
Drew Reese

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

Related Questions