Skip to content

Instantly share code, notes, and snippets.

@donavon
Created April 7, 2020 13:57
Show Gist options
  • Save donavon/ab232666df8a459235365546b3c2c5fa to your computer and use it in GitHub Desktop.
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.
// Example component using StateRouter
const MyComponent = () => {
const [state] = useMachine(myMachine);
return (
<StateRouter state={state}>
<Loading path="loading" />
<Ready path="ready" />
<Error path="error" />
</StateRouter>
);
};
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