Created
April 7, 2020 13:57
-
-
Save donavon/ab232666df8a459235365546b3c2c5fa to your computer and use it in GitHub Desktop.
StateRouter for rendering one or more children where `state` is found in the`path` prop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example component using StateRouter | |
const MyComponent = () => { | |
const [state] = useMachine(myMachine); | |
return ( | |
<StateRouter state={state}> | |
<Loading path="loading" /> | |
<Ready path="ready" /> | |
<Error path="error" /> | |
</StateRouter> | |
); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const StateRouter = ({ state, children }) => { | |
const elements = React.Children.toArray(children); | |
const filteredChildren = elements.reduce((arr, child) => { | |
const { path = '' } = child.props; | |
return path | |
.split(' ') | |
.includes(state) | |
? [...arr, child] | |
: arr; | |
}, []); | |
if (filteredChildren.length) { | |
return filteredChildren; | |
} | |
throw new Error(`No routes not found for ${state}`); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment