Search code examples
reactjsreach-router

How to create List/Detail view with reach/router


Since reach/router doesn't support optional params, how would you go about creating a view like this?

┌────────────────┐┌────────────────────────────────────────────────┐
│ ┌────────────┐ ││                                                │
│ │   Book 1   │ ││  Book 2                                        │
│ └────────────┘ ││  Name: Unknown knowns                          │
│ ┌────────────┐ ││  Author: Donald                                │
│ │ √ Book 2   │ ││  Year: 2001                                    │
│ └────────────┘ ││  ISBN: 666                                     │
│ ┌────────────┐ ││                                                │
│ │   Book 3   │ ││                                                │
│ └────────────┘ ││                                                │
│ ┌────────────┐ ││                                                │
│ │   Book 4   │ ││                                                │
│ └────────────┘ ││                                                │
│ ┌────────────┐ ││                                                │
│ │   Book 5   │ ││                                                │
│ └────────────┘ ││                                                │
└────────────────┘└────────────────────────────────────────────────┘

On the left there is a list of Books that should be rendered either:

  • at /books
  • at /books/:isbn

On the right the box shows Details of a book if at /books/:isbn and it's shows an empty box if at /books.


Solution

  • Just figured it out. This can be done with Embedded Routers and Wildcards like:

    function App() {
      return (
        <Router>
          <Books path='/books/*' />
        <Router>
      );
    }
    
    function Books() {
      return (
        // ... left-side list here
        <Router>
          <BookDetail path=':isbn' />
        <Router>
      );
    }