Skip to content

Instantly share code, notes, and snippets.

@alexindigo
Created July 5, 2016 00:42
Show Gist options
  • Save alexindigo/7fed9458ca418bc3295244ca28b59ce0 to your computer and use it in GitHub Desktop.
Save alexindigo/7fed9458ca418bc3295244ca28b59ce0 to your computer and use it in GitHub Desktop.
import React, { PropTypes } from 'react'
import ReactDOM from 'react-dom'
// A/B Testing "wrapper"
const ABTester = React.createClass({
render() {
let output = (
<div>
<div>A/B Test All The Things!</div>
<div>{this.props.children}</div>
</div>
);
// Need to augment this output based on A/B testing logic
// but it's not being triggered on internal components updates
return output;
}
})
// ------ REGULAR APP GOES BELOW -----
const tabType = PropTypes.shape({
label: PropTypes.string.isRequired,
content: PropTypes.string.isRequired
})
const countryType = PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
description: PropTypes.string.isRequired
})
const styles = {}
styles.tab = {
display: 'inline-block',
padding: 10,
margin: 10,
borderBottom: '4px solid',
borderBottomColor: '#ccc',
cursor: 'pointer'
}
styles.activeTab = {
...styles.tab,
borderBottomColor: '#000'
}
styles.panel = {
padding: 10
}
// ---- Wrapped component, that has it's own components ----
const App = React.createClass({
propTypes: {
countries: PropTypes.arrayOf(countryType).isRequired
},
render() {
const data = this.props.countries.map(country => ({
label: country.name,
content: country.description
}))
return (
<div>
<h1>Countries</h1>
<Tabs data={data}/>
</div>
)
}
})
// --- Sub-component of the wrapped component ---
// --- Has it's own state ---
// --- Updates happen on this level, without propagating all the way to the top ---
const Tabs = React.createClass({
propTypes: {
data: PropTypes.arrayOf(tabType)
},
getInitialState() {
return {
activeTabIndex: 0
}
},
selectTabIndex(activeTabIndex) {
this.setState({
activeTabIndex
})
},
render() {
const { data } = this.props
const { activeTabIndex } = this.state
const tabs = data.map((tab, index) => {
const isActive = index === activeTabIndex
const style = isActive ? styles.activeTab : styles.tab
return (
<div
key={tab.label}
className="Tab"
style={style}
onClick={() => this.selectTabIndex(index)}
>{tab.label}</div>
)
})
const activeTab = data[activeTabIndex]
const content = activeTab && activeTab.content
return (
<div className="Tabs">
{tabs}
<div className="TabPanel" style={styles.panel}>
{content}
</div>
</div>
)
}
})
// --- Adding things to the page
const DATA = [
{ id: 1, name: 'USA', description: 'Land of the Free, Home of the brave' },
{ id: 2, name: 'Brazil', description: 'Sunshine, beaches, and Carnival' },
{ id: 3, name: 'Russia', description: 'World Cup 2018!' }
]
ReactDOM.render(
<ABTester>
<App countries={DATA}/>
</ABTester>, document.getElementById('app'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment