Not found routing
To handle "not found" route behavior, you can achieve this using theReact
component<RouteViewGroup />
along with either aReact
component orVirtualRoute
.
There are two ways to implement "not found" routing behaviour:
Redirect to another route
- Create an instance of the
VirtualRoute
class
In the behavior of this virtual route, it's crucial to implement a redirect to an existing route, for example, to the "home" page.
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:
returnfalse;
- Connect this
notFoundRoute
to your<RouteViewGroup />
component usingotherwise
prop
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:
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-model
and the<OnlyViewModel />
component.
Not found page
- Create an instance of the
VirtualRoute
class
import{ VirtualRoute }from"mobx-route";exportconstnotFoundRoute=newVirtualRoute({})
- Connect this
notFoundRoute
to your<RouteViewGroup />
component usingotherwise
propand createRouteView
for this route
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>)}