How can a Tab2 know, during render, if it's the currently selected tab?

208 views Asked by At

How can a Tab2 know, during render, if it's the currently selected tab?

I want to do this to change the content or style of the tab title (e.g., the selected tab's title is italicized).

I'd prefer not to use onChange and manage the Tab2 state, as Tab2 already knows its own state.

  <Tabs2 id="TabPane">
    <Tab2
      id="TabFirst"
      panel={SomePanel}
    >
      <Text>
       { isCurrentTabId("TabFirst") 
          ? "I am selected!" 
          : "I'm not selected"}
     </Text>
    </Tab2>
    <Tab2 id="TabSecond"/>
  </Tabs2>


const isCurrentTabId = (tabId) => { ??? }; 

What code goes where the "???" is?

Thanks!

1

There are 1 answers

0
Sagiv b.g On

I think you need to rethink your approach.
The parent Component should know which tab is selected and not the tab itself.

Lets say the tab itself will know if it selected via an onClick event or whatever other approach, OK then, you render the style like you wanted.
Now, what happens when i click Tab5? it will know that it is the selected tab, but what about the first tab? who will notify it that its not selected anymore?

I think it's the parent of all Tabs responsibility to manage who is the selected Tab, and the parent can pass down a prop for each tab, like isSelected for example to notify it if it selected or not.

A small example:

const tabs = [1, 2, 3, 4, 5];


class Tab extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = this.onClick.bind(this);
  }


  onClick() {
    const { id, onClick } = this.props;
    onClick(id);
  }

  render() {
    const { id, isSelected } = this.props;
    const css = `tab ${isSelected && 'selected'}`;
    return (
      <div
        className={css}
        onClick={this.onClick}
      >
      Tab - {id}
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedTab: 1
    }

    this.onTabChange = this.onTabChange.bind(this);
  }

  onTabChange(id) {
    this.setState({ selectedTab: id });
  }

  render() {
    const { selectedTab } = this.state;
    return (
      <div>
        {
          tabs.map((t, i) => <Tab id={i + 1} isSelected={selectedTab === i + 1} onClick={this.onTabChange} />)
        }
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.tab{
  display: inline-block;
  margin: 0 10px;
  width: 60px
  text-align: center;
  cursor: pointer;
}

.selected{
  border: 1px solid #eee;
  box-shadow: 0 0 3px 1px #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>