Ad

How To Pass State Value From Parent Element To Child In React

- 1 answer

In my code I have a tab menu and I want to switch in between these tabs using a button. I want to pass the value of these tabs into my onclick function for my button so it can navigate between the tabs.

For example:

<Tabs value={this.state.value} onChange={this._handleChange}>
     <Tab label="1" value={1}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
     <Tab label="2" value={2}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
     <Tab label="3" value={3}>
         <RaisedButton label="Next" onTouchTap={this._handleChange} />
     </Tab>
</Tabs>

My _handleChange function simply sets the state to the value of the next tab

_handleChange: function(value) {
    this.setState({
      value: value,
    });
    console.log(this.state);
  }

I need to somehow linkup the onTouchTap event with the onChange event from the main tabs element but I am not sure how to do that. My main goal is to navigate between the three tabs available: when the next button is clicked on tab1, it will shift to tab2, and then onto tab3, and finally back to tab1.

Does anyone know how I can accomplish that? I am also using material UI if those elements look foreign.

Ad

Answer

You can do it like this:


<Tabs value={this.state.value} onChange={this._handleChange}>
     <Tab label="1" value={1}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 2)} />
     </Tab>
     <Tab label="2" value={2}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 3)} />
     </Tab>
     <Tab label="3" value={3}>
         <RaisedButton label="Next" onTouchTap={this._handleChange.bind(this, 1)} />
     </Tab>
</Tabs>
Ad
source: stackoverflow.com
Ad