ruby-on-railsrubyreactjsopalrbhyperstack

Setting active state on a Nav item depending on the Route using ReactBootstrap


What is the best way of ensuring the correct Nav Item is selected using React Bootstrap and Hyperstack Router?

I know I can the Link method, but I want to use the specific Bootstrap Nav item instead.

Is there a good example of this anyone can share?


Solution

  • React router actually handles this automatically! I have used this in one of my apps, maybe it can help for inspiration:

    class BS < Hyperstack::Component::NativeLibrary
      # subclasses of Hyperstack::Component::NativeLibrary
      # are wrappers around JS component libraries.
      # once imported BS acts like an ordinary ruby module
    
      imports 'ReactBootstrap'
    end
    
    class App < HyperComponent
      include Hyperstack::Router
      include Hyperstack::Router::Helpers
    
      ROUTES = {
        '/' => ['Home', Home],
        '/overview' => ['Overview', Overview]
      }
    
      render do
        DIV {
          H1 { "Hello there from Hyperstack!" }
          BS::Nav(variant: 'pills') {
            ROUTES.each do |k, v|
              BS::Nav.Item() {
                NavLink(k, class: 'nav-link', exact: true) { v[0] }
              }
            end
          }
          ROUTES.each do |k, v|
            Route(k, mounts: v[1], exact: true)
          end
        }
      end
    end