There are a lot of examples of code online where you build tabs like:
<Container>
<Tab title="Tab A">
{"Tab A content"}
</Tab>
<Tab title="Tab A">
{"Tab B content"}
</Tab>
</Container>
This works reasonably well for simple use cases. You could imagine that Container
is sort of implemented as something like this:
const Tab = (props) => (
<div>{props.title}</div>
)
const Container = (props) => {
const items = props.children
const selectedContent = props.children[props.selectedIdx].children
return (
<div>
{items}
{selectedContent}
</div>
)
}
const App = () => {
const [idx, selectedIdx] = React.useState(0)
return (
... the previous code blox
)
}
But let's say we want to have our tabs be a little more complex. Each tab has various network requests, and the tab titles might be different depending on the output of the network request. Rather than have all the data fetching logic in this parent component I'd like something like:
<Container>
<TabOneWithDataFetching/>
{....}
<TabNWithDataFetching/>
</Container>
const TabOneWithDataFetching = () => {
const content = // make network request
const title = // make network request
return <Tab title={title}>{content}</Tab>
}
However, when I do something like this it seems to make rendering the selected content from the Container
component really difficult. I can no longer do props.children[index].children
and typing this becomes a mess too. Am I approaching this incorrectly? Is this the wrong way of thinking about components and modularity?