Skip to content

Not found routing

To handle "not found" route behavior, you can achieve this using theReactcomponent<RouteViewGroup />along with either aReactcomponent orVirtualRoute.

There are two ways to implement "not found" routing behaviour:

Redirect to another route

  1. Create an instance of theVirtualRouteclass

In the behavior of this virtual route, it's crucial to implement a redirect to an existing route, for example, to the "home" page.

ts
import{ VirtualRoute }from"mobx-route";import{ homeRoute }from"@/pages/home"exportconstnotFoundRoute=newVirtualRoute({asyncopen() {awaithomeRoute.open(null, { replace:true});returnfalse;}})

It's also importantnotto physically change the "open" state of this route. This line achieves that:

ts
returnfalse;
  1. Connect thisnotFoundRouteto your<RouteViewGroup />component usingotherwiseprop
tsx
import{ RouteViewGroup, RouteView }from"mobx-route/react"import{ notFoundRoute }from"@/pages/not-found"...exportconstApp=()=>{...return(<RouteViewGroupotherwise={notFoundRoute}><RouteViewroute={homeRoute}view={HomePage} /></RouteViewGroup>)}

This way, when the<RouteViewGroup/>component determines that no internal route is open, it will open thenotFoundRoute.

Alternative Approach

You can simply specify as the last child element in the<RouteViewGroup />component a component that will render when no route is open:

tsx
import{ RouteViewGroup, RouteView }from"mobx-route/react"import{ homeRoute }from"@/pages/home"import{ useEffect }from"react"...constNotFoundComponent=()=>{useEffect(()=>{homeRoute.open(null, { replace:true});}, [])returnnull}exportconstApp=()=>{...return(<RouteViewGroup><RouteViewroute={homeRoute}view={HomePage} /><NotFoundComponent/></RouteViewGroup>)}

You can also usemobx-view-modeland the<OnlyViewModel />component.

Not found page

  1. Create an instance of theVirtualRouteclass
ts
import{ VirtualRoute }from"mobx-route";exportconstnotFoundRoute=newVirtualRoute({})
  1. Connect thisnotFoundRouteto your<RouteViewGroup />component usingotherwisepropand createRouteViewfor this route
tsx
import{ RouteViewGroup, RouteView }from"mobx-route/react"import{ notFoundRoute }from"@/pages/not-found"...exportconstApp=()=>{...return(<RouteViewGroupotherwise={notFoundRoute}><RouteViewroute={homeRoute}view={HomePage} /><RouteViewroute={notFoundRoute}view={NotFoundPage} /></RouteViewGroup>)}

Released under the MIT License.