1

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.

Amir-Mousavi
  • 4,273
  • 12
  • 70
  • 123

1 Answers1

3

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.

zhuber
  • 5,364
  • 3
  • 30
  • 63
  • This is not react-router, it is [REACH ROUTER](https://reach.tech/router/tutorial/06-nesting) – Amir-Mousavi Oct 22 '19 at 15:59
  • Thanks, it works, though introducing an empty component is a bit wired, but I am in the middle of the project and there is no other way around :) – Amir-Mousavi Oct 23 '19 at 09:02
  • I agree, maybe with a little better wording it would look more nicely, something like 'Placeholder' maybe. – zhuber Oct 23 '19 at 09:09
  • 1
    Yes, wording and in early stages, I could have some functionalities in that per say `wrapper` or `placeholder` like some interfaces or functions that all children will need, That will look more professional and happier project manager :D – Amir-Mousavi Oct 23 '19 at 10:33