— Feature Card
Description
Right now users have to do routing like this:
{(data.isFetching && <Loading />) ||
(data.isArchive && <Archive data={data} />) ||
(data.isPage && <Page data={data} />) ||
(data.isPostType && <Post data={data} />) ||
(data.is404 && <Page404 />)}
With a simple Switch
component, it will be much clearer:
<Switch>
<Loading when={data.isFetching} />
<Archive when={data.isArchive} />
<Page when={data.isPage} />
<Post when={data.isPostType} />
<Page404 />
</Switch>
User Stories
As a theme developer
I want to route between pages with a <Switch> component
so that I don’t have to use plain JavaScript logic
Possible solution
Reach Router has this type of component. It is implemented using React.Children.toArray(children)
to iterate over children and check for the path
prop in the element.props
. In our case, we could check for when
.
@Segun, as we talked today a little bit about improving the way routing works in Frontity, would you mind sharing your impressions about this Switch
component? Do you see any limitations? Would you use a different approach?
@luisherranz What’s the plan for this? Can we have a call to talk about it? I would love to work on it.
Sure! Let me know your questions
Have you discussed any further details @iamuchejude @luisherranz ?
@iamuchejude can you give us an update on this? How is it going?
@luisherranz The work on this feature has been going well. After hours of contemplations and researches on how it should work, I was able to write a component whose children accepts in either of 2 props; that is, either path
(URI path) or when
(boolean) props to conditionally render the children components.
Usage
import Switch from "@frontity/components/switch";
const TestSwitch = ({ state }) => {
const data = state.source.get(state.router.link);
return (
<Switch>
/* With 'when' prop */
<Loading when={data.isLoading} />
<Archive when={data.isArchive} />
<Error when={data.isError} />
/* With 'path' prop */
<CustomPage path="/custom" />
/* WIP: The last component without props should be rendered if no matching component was found (404) page */
<ErrorComponent />
</Switch>
);
}
At the moment, I’m trying to figure out a better way to handle errors (The current implementation doesn’t seem to handle edge some cases) with the switch components. The path
prop will also need a review before I’ll proceed with fixing the issues with it.
1 Like