I am using Reach router in the React app (with typescript).
using nested routes I got stuck in how to render the nested component as a separate (in separate view) component and not as the child at the bottom of the parent component.
The code is like:
App.tsx
--------
<Router>
<Customers path="/customers">
<PDFExport path=":id" />
</Customers>
<Users path="/users">
<PDFExport path=":id" />
</Users>
</Router>
Customers.tsx
--------------
interface IProps extends RouteComponentProps {children: any;}
const Customers: React.FC<IProps> = props => {
const[customers,setCustomers]=React.useSate(); // somehow fetch custmers
return (
<>
{customers.map(c=>(
<Button as={Link} to={`${c.id}`} />)
}
// on click the url chages to i.g. `/customers/123`
// but I do not get navigated to the PDFExport component
// but I have to render that here as child like follow
{props.childern}
// in this case I will have the content of PDFExport component at the bottom of Customers component
</>
);
}
PDFExport.tsx
-------------
interface IProps extends RouteComponentProps {
id?: string;
}
const PDFExport: React.FC<IProps> = props => {
return <div>{props.id}</div>;
// this will contain the comon form I want to use for different parents
};
The reason why I have used the PDFExport as nesting is that I wan to reuse it for different routes like; /users/:id
, /customers/:id
.
Is there any way to render the nested route as a separate component not as the child.
You can try something like this:
const Empty = ({ children }) => {
return children;
}
<Router>
<Empty path="/customers">
<Customers path="/" />
<PDFExport path=":id" />
</Empty>
<Empty path="/users">
<Users path="/" />
<PDFExport path=":id" />
</Empty>
</Router>
When you define nested component with /
path, it will be used as index component for that parent. Since we have empty parent, you'll have that index component displayed. Once you navigate to :id
, you'll get that component within parent, which again is empty component.
Please see under Index Routes.