Last active
August 24, 2018 09:09
-
-
Save na0x2c6/b7f7c305040264d1d97ce421bf4b55e4 to your computer and use it in GitHub Desktop.
HOC Sample 2: Props Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function withSubscription(WrappedComponent, selectData) { | |
return class extends React.Component { | |
constructor(props) { | |
super(props) | |
this.handleChange = this.handleChange.bind(this) | |
this.state = { | |
data: selectData(DataSource, props) | |
} | |
} | |
componentDidMount() { | |
DataSource.addChangeListener(this.handleChange) | |
} | |
componentWillUnmount() { | |
DataSource.removeChangeListener(this.handleChange) | |
} | |
handleChange() { | |
this.setState({ | |
data: selectData(DataSource, this.props) | |
}) | |
} | |
render() { | |
return <WrappedComponent data={this.state.data} {...this.props} /> | |
} | |
} | |
} | |
const Card = ({ card }) => ( | |
<div className="card"> | |
<div className="card-content" style={{ color: card.color }}> | |
{card.name} | |
</div> | |
</div> | |
) | |
const List = ({ list, data }) => { | |
return ( | |
<div className="column" | |
style={{ backgroundColor: list.color }}> | |
<header>{`${list.name} (id:${list.id})`}</header> | |
{data.map((card, idx) => | |
<Card card={card} key={idx} /> | |
)} | |
</div> | |
) | |
} | |
const ListWithSubscription = withSubscription( | |
List, | |
(DataSource, props) => DataSource.getCards(props.list.id) | |
) | |
const Board = ({ data }) => { | |
return ( | |
<div className="columns"> | |
{data.map(list => | |
<ListWithSubscription list={list} key={list.id} /> | |
)} | |
</div> | |
) | |
} | |
const BoardWithSubscription = withSubscription( | |
Board, | |
(DataSource) => DataSource.getLists() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment