Skip to content

Instantly share code, notes, and snippets.

@leoasis leoasis/index.js
Created Jan 26, 2017

Embed
What would you like to do?
Pinterest example using upcoming React's coroutines
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
You can’t perform that action at this time.