Created
January 26, 2017 21:53
-
-
Save leoasis/ec77e3a65fd6f5274b647daa0803ce87 to your computer and use it in GitHub Desktop.
Pinterest example using upcoming React's coroutines
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
import React, { Component } from 'react'; | |
import ReactDOM from 'react-dom/lib/ReactDOMFiber'; | |
import { createCoroutine, createYield } from 'react-dom/lib/ReactCoroutine'; | |
function Pin(props) { | |
return createYield( | |
{ height: props.height + 10 }, | |
() => { | |
return ( | |
<div | |
style={{ | |
flexBasis: props.height, | |
padding: 5, | |
margin: 5, | |
backgroundColor: props.height < 150 ? '#EEDDCC' : '#CCDDEE' | |
}} | |
> | |
Pin ({props.height}px) | |
</div> | |
) | |
} | |
); | |
} | |
function Board(props) { | |
return createCoroutine( | |
props.children, | |
(props, yields) => { | |
let columnHeights = [0, 0, 0, 0]; | |
let columns = [[], [], [], []]; | |
yields.forEach((y) => { | |
const columnIndex = columnHeights.indexOf(Math.min.apply(null, columnHeights)); | |
columnHeights[columnIndex] += y.props.height; | |
columns[columnIndex].push(<y.continuation />); | |
}); | |
return ( | |
<div style={{ display: 'flex' }}> | |
{columns.map((els) => ( | |
<div | |
style={{ | |
flex: 1, | |
display: 'flex', | |
flexDirection: 'column' | |
}} | |
> | |
{els} | |
</div> | |
))} | |
</div> | |
); | |
}, | |
props | |
) | |
} | |
class CoRoutinesPinterest extends Component { | |
state = { | |
pins: [200, 50, 300, 100, 150] | |
}; | |
componentDidMount() { | |
setInterval(() => { | |
this.setState((state) => ({ | |
pins: state.pins.concat(50 + Math.floor((Math.random() * 300))) | |
})); | |
}, 2000); | |
} | |
render() { | |
return [ | |
<Board> | |
{this.state.pins.map((height) => <Pin height={height} />)} | |
</Board> | |
]; | |
} | |
} | |
ReactDOM.render( | |
<CoRoutinesPinterest />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment