Reputation: 85
I am using react 17.0.2 and have defined routes like this:
export const PATH = {
editProduct: '/edit-product/:productId'
}
export const routes = [
{
path: PATH.editProduct,
render: (props) => <Product {...props}/>
}
]
export const useRoutes = () => ({ PATH, routes });
The routes are then used with 'react-router-dom' version: ^5.2.0
Some previous paths without routeparams uses history.push(PATH.somePath);
and it works, but I would like to use the react routerParams in some component.
Like:
history.push({pathname: PATH.editProduct, routerParam: {productId: "2"} });
Previous paths with routeparams have been passed by not using PATH variable, but instead typing the string like history.push('/edit-product/' + productId);
I would want to reuse the PATH variables, but I can't figure out how it could be achieved smartly.
If I use PATH.editProduct in history.push method, it places the routeparam along with it like /edit-product/:productId, which is not the behaviour I am looking for. Is there parsing method in history for routeparams?
Upvotes: 3
Views: 245
Reputation: 2586
There is generatePath
util in react-router-dom
.
import { generatePath } from "react-router-dom";
const path = generatePath(PATH.editProduct, {
productId: 1
});
history.push(path);
https://reactrouter.com/web/api/generatePath
Upvotes: 5