Skip to content

Instantly share code, notes, and snippets.

@DZuz14 DZuz14/Slider.js
Last active Oct 4, 2018

Embed
What would you like to do?
Slide Width Calculation
import React, { Component } from 'react'
import Slide from '../slide'
import LeftArrow from '../left-arrow'
import RightArrow from '../right-arrow'
export default class Slider extends Component {
constructor(props) {
super(props)
this.state = {
images: [
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/aurora.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/canyon.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/city.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/desert.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/mountains.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/redsky.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/sandy-shores.jpg",
"https://s3.us-east-2.amazonaws.com/dzuz14/thumbnails/tree-of-life.jpg"
],
currentIndex: 0,
translateValue: 0
}
}
goToPrevSlide = () => {
}
goToNextSlide = () => {
// Exiting the method early if we are at the end of the images array.
// We also want to reset currentIndex and translateValue, so we return
// to the first image in the array.
if(this.state.currentIndex === this.state.images.length - 1) {
return this.setState({
currentIndex: 0,
translateValue: 0
})
}
// This will not run if we met the if condition above
this.setState(prevState => ({
currentIndex: prevState.currentIndex + 1,
translateValue: prevState.translateValue + -(this.slideWidth())
}));
}
slideWidth = () => {
return document.querySelector('.slide').clientWidth
}
render() {
return (
<div className="slider">
<div className="slider-wrapper"
style={{
transform: `translateX(${this.state.translateValue}px)`,
transition: 'transform ease-out 0.45s'
}}>
{
this.state.images.map((image, i) => (
<Slide key={i} image={image} />
))
}
</div>
<LeftArrow
goToPrevSlide={this.goToPrevSlide}
/>
<RightArrow
goToNextSlide={this.goToNextSlide}
/>
</div>
);
}
}
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.