I am trying to achieve child/nested routes in Reactjs and below are the 2 methods which I found for nesting the child routes but parent routes work fine and child routes for Parent component do not.
Below are the routes how it works:
/ => Home Component
/login => Login Component
/register => Register Componet
/product/ => ProductListing Component
/product/2 => ProductDetails Component [Expected but does not work]
/product/2/edit => ProductEdit Component [Expected but does not work]
Method 1
Below is my Main Route File:
export default function MainRouter() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/product" component={ProductRouter} />
</Router>
);
}
and child route for Product as shown below in ProductRouter.js file
export default function ProductRouter(props) {
console.log(props);
return (
<Switch>
<Route
exact
path={`${props.match.path}/:productId`}
component={ProductDetails}
/>
<Route
exact
path={`${props.match.path}/:productId/edit`}
component={ProductEdit}
/>
<Route exact path={`${props.match.path}`} component={ProductListing} />
</Switch>
);
}
Method 2
Below is my Main Route File:
export default function MainRouter() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<Route exact path="/register" component={Register} />
<Route exact path="/product/*" component={ProductRouter} />
</Router>
);
}
and child route for Product as shown below in ProductRouter.js file
export default function ProductRouter(props) {
return (
<Fragment>
<Route exact path="/" component={ProductListing} />
<Route
exact
path=":productId"
component={ProductDetails}
/>
<Route
exact
path=":productId/edit"
component={ProductEdit}
/>
</Fragment>
);
}
Below are the links I checked: