Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created October 5, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/c8d178eec00282f3b8005b35e3f68e38 to your computer and use it in GitHub Desktop.
Save mjackson/c8d178eec00282f3b8005b35e3f68e38 to your computer and use it in GitHub Desktop.
import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
function ContentToggle(props) {
let summaryClassName = 'ContentToggle__Summary'
if (props.isOpen)
summaryClassName += ' ContentToggle__Summary--is-open'
return (
<div style={props.style} className="ContentToggle">
<button onClick={props.onToggle} className={summaryClassName}>
{props.summary}
</button>
<div className="ContentToggle__Details">
{props.isOpen && props.children}
</div>
</div>
)
}
class StatefulContentToggle extends React.Component {
state = {
isOpen: false
}
render() {
return (
<ContentToggle
{...this.props}
isOpen={this.state.isOpen}
onToggle={() => this.setState({ isOpen: !this.state.isOpen })}
/>
)
}
}
class App extends React.Component {
state = {
tacos: [
{ id: 0, name: 'Carnitas', src: 'tacos/carnitas.png', isOpen: false },
{ id: 1, name: 'Pollo', src: 'tacos/pollo.png', isOpen: false },
{ id: 2, name: 'Asada', src: 'tacos/asada.png', isOpen: false }
]
}
toggleAll = (isOpen) => {
this.setState(state => ({
tacos: state.tacos.map(t => {
t.isOpen = isOpen
return t
})
}))
}
toggleTaco = (taco, isOpen) => {
this.setState(state => ({
tacos: state.tacos.map(t => {
if (t === taco)
t.isOpen = isOpen
return t
})
}))
}
render() {
const allOpen = this.state.tacos.every(t => t.isOpen)
return (
<div>
<button
onClick={() => this.toggleAll(!allOpen)}
>{allOpen ? 'Close' : 'Open'} all</button>
<div>
{this.state.tacos.map((taco) => (
<ContentToggle
key={taco.name}
style={{ width: 300 }}
summary={taco.name}
isOpen={taco.isOpen}
onToggle={() => this.toggleTaco(taco, !taco.isOpen)}
>
<div
style={{
height: 200,
background: `url(${taco.src})`,
backgroundSize: 'cover'
}}
/>
</ContentToggle>
))}
</div>
<StatefulContentToggle summary="Carnitas">
<div
style={{
height: 200,
background: `url(tacos/carnitas.png)`,
backgroundSize: 'cover'
}}
/>
</StatefulContentToggle>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment