1

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?

mj435235
  • 11
  • 1
  • This would probably be easier using react-router. – Christian Fritz May 10 '21 at 21:21
  • I wonder what job `Container` is really doing here. I imagine that all you really need is some kind of switch component to do control flow between tabs, which you could do via a routing library to tie it to the URL, but it is not hard to implement without routing by yourself (some useful examples in [this thread](https://stackoverflow.com/a/60313570/12799351)). Accessing `props.children[index].children` is definitely not the way to go. – lawrence-witt May 10 '21 at 21:51

1 Answers1

0

I think you are close, React is very much about state management for components. If you are using bootstrap, you could take a look at React Bootstraps' Tab implementation.

Maybe some non-bootstrap libraries could be used for tabbed content.

Leroy
  • 1,600
  • 13
  • 23