tleunen / react-mdl

React Components for Material Design Lite
https://tleunen.github.io/react-mdl/
MIT License
1.76k stars 255 forks source link

What's the best way to integrate Tabs with react-router? #355

Closed igorsantos07 closed 8 years ago

igorsantos07 commented 8 years ago

I would like to use the MDL Tabs for my application that uses react-router for navigation...

Initially I was using the pure JS, but had some trouble with its events. Then, I found this library, but the best I could do still seems quite ugly:

export default class NavigationBar extends Component {

  constructor(props) {
    super(props)
    this.state = {
      active: 0
    }
  }

  //FIXME: holy cow there MUST be a better way to use Tabs for navigation!
  onChange(id) {
    let node = findDOMNode(this)
    let path = node.children[0].children[id].attributes.to.nodeValue
    this.setState({ active: id })
    hashHistory.push(path)
  }

  render() {
    return (
      <Tabs ripple activeTab={this.state.active} onChange={this.onChange.bind(this)}>
        <Tab to="/">Home</Tab>
        <Tab to="/stuff">Stuff</Tab>
        <Tab to="/etc">Etc</Tab>
      </Tabs>
    )
  }

}

My first thought was something like <Tab><Link to="/">Home</Link></Tab> but that triggers an error because there is an anchor inside another :(

tleunen commented 8 years ago

Indeed, you can pass a custom component prop to the component to specify the component you want.

<Tab component={Link} to="/">Home</Tab>

But to be honest, I'm not a huge fan of this syntax. Instead, it should be the way you thought it was. This will probably be updated in v2 ;)

Note that you'd still need to listen for a onChange event on the Tabs component to setup the right active tab for the styles.

igorsantos07 commented 8 years ago

@tleunen, I was re-reading this issue here and got an idea. Shouldn't that be default to the Tabs/HeaderTabs+Tab components? Or would it be too hard to implement?

I mean, Tab could have an internal onClick behaviour that would give its ID to the parent component - that should always be one of the Tabs implementation, and the correct active tab would be set without developer intervention. I can't see a case where there would be no need for tabs to change into active hmmm There's also Tab.active to be used in this case.. Could be even simpler/decoupled to implement.

If you think this makes sense, I can move this into a new issue. Not sure I could help coding as I'm pretty new to React libs (even React apps themselves are new for me). :smile:

tleunen commented 8 years ago

Yes I agree, Tabs should automatically set the active state on one of its children, and thus avoid the end user of doing it.

I wonder if this could be done in v1.x without creating a breaking change, because users are already using an onclick to setup the active tab (mostly only for the active purpose I guess because most users would probably use something like react router)