How can I avoid mapping over Children while completing the Tabs example?
amite opened this issue Β· comments
Hey @mjackson @ryanflorence π
While completing your Tabs example in the Advanced React course, I ported it to the new Context api: https://codesandbox.io/s/01p15lx5rn
But this mapping over children is still bothering me.
<TabsContext.Consumer>
{({ activeIndex, onActivate }) => {
const children = React.Children.map(
this.props.children,
(child, index) =>
React.cloneElement(child, {
isActive: index === activeIndex,
onClick: () => onActivate(index)
})
);
return <div style={styles.tabList}>{children}</div>;
}}
</TabsContext.Consumer>
Mapping over children to pass them props might end up breaking the ui and the api contract for children if someone inserts a div
in between. How do I pass onClick and isActive flag to children without mapping over children?
I there any way to avoid it? π
@amite I ran into the same issue when working with the react-tabs
library when trying to nest tabs. I created my own package that handles nested tabs.
To do this, you'll need to do some refactoring. Instead of iterating through an array of children, we can use an object
to keep track of what tab is active. Some cool benefits come out of this.
- the
TabList
andTabPanels
are no longer necessary - the relationship between
Tab
andTabPanel
is more explicit. Previously, the relationship was implicit in the order they appeared. Now, their relationship is explicit in theid
s they share.
Take a look at this CodeSandbox demo.
If you're using context you shouldn't need to map over the children at all. The whole point of context is to enable parent/descendant communication so you don't have to pass props directly. You can see an iteration from mapping over the children to using context in the context lecture.