Skip to content

Instantly share code, notes, and snippets.

@esshka
Created March 21, 2016 01:06
Show Gist options
  • Save esshka/d5d29fa7caed2c17b231 to your computer and use it in GitHub Desktop.
Save esshka/d5d29fa7caed2c17b231 to your computer and use it in GitHub Desktop.
simple carousel on react
state = {
offset: 0,
items: [],
itemsVisible: 4,
width: 800,
height: 100,
};
componentDidMount() {
this.setState({items: initialItems})
}
toLeft = () => {
const {offset, items, itemsVisible} = this.state;
if (offset < items.length - itemsVisible) {
this.setState({offset: this.state.offset + 1});
}
};
toRight = () => {
const {offset, } = this.state;
if (offset > 0) {
this.setState({offset: this.state.offset - 1});
}
};
render() {
const { offset, items, width, itemsVisible, height } = this.state;
const itemWidth = width / itemsVisible;
return (
<div className="App">
<div className="carousel" style={{width: width + 200, padding: "0 100px"}}>
<div className="items" style={{width, height}}>
{items.map((item, idx) => (
<div
className="item"
key={item.id}
style={{
transform: `translateX(${itemWidth * idx - itemWidth * offset}px)`,
transition: 'transform 1s',
width: itemWidth,
height: height,
}}>
<div className="item-content" >
<img src={item.img} alt="" width="100%"/>
</div>
</div>
))}
</div>
<div className="nav">
<span className="nav-item nav-items-left" onClick={this.toLeft}>left</span>
<span className="nav-item nav-items-right" onClick={this.toRight}>right</span>
</div>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment