Skip to content

Instantly share code, notes, and snippets.

@mattlo
Last active April 18, 2016 21:06
Show Gist options
  • Save mattlo/aebd08abe77d1a072d3cb90831583165 to your computer and use it in GitHub Desktop.
Save mattlo/aebd08abe77d1a072d3cb90831583165 to your computer and use it in GitHub Desktop.
React Tabs /w Redux
import './VideoInfo.scss';
import React from 'react';
import Tabs from '../Tabs/Tabs';
import TabsItem from '../Tabs/TabsItem';
export default class VideoInfo extends React.Component {
render() {
return (
<div>
<Tabs id="videoInfoTab">
<TabsItem title="Hello World">
Content 1
</TabsItem>
<TabsItem title="Hello World 2">
Content 2
</TabsItem>
</Tabs>
</div>
);
}
}
import './Tabs';
import React from 'react';
import {connect} from 'react-redux';
import TabsHeader from './TabsHeader';
class Tabs extends React.Component {
static propTypes = {
children: React.PropTypes.node,
className: React.PropTypes.string,
id: React.PropTypes.string.isRequired,
activeIndex: React.PropTypes.number
};
static idList = [];
constructor(props) {
super(props);
if (Tabs.idList.indexOf(props.id) >= 0) {
throw new Error(`${props.id} is already in use, use a different id`);
}
Tabs.idList = [...Tabs.idList, props.id];
}
isActive(index) {
return this.props.activeIndex === index;
}
render() {
const className = this.props.className ? this.props.className : '';
const children = React.Children.toArray(this.props.children);
return (
<div className={`tabs ${className}`}>
<div className="tabs-header">
{children.map((tabItem, index) => (
<TabsHeader
title={tabItem.props.title}
id={this.props.id}
key={index}
index={index}
active={this.isActive(index)}
/>
))}
</div>
<div className="tabs-items">
{children.map((Cmp, index) => React.cloneElement(
Cmp,
{active: this.isActive(index)}
))}
</div>
</div>
);
}
}
export default connect((state, props) => ({
activeIndex: state.tab[props.id] || 0,
...props
}))(Tabs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment