Last active
April 3, 2019 22:19
-
-
Save ooade/df8d30154de2ec7130b0a6d0bd79d3c4 to your computer and use it in GitHub Desktop.
Carousel / Slider
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
class Slider extends React.Component { | |
state = { | |
index: 0 | |
}; | |
invokeInterval = () => { | |
this.setState({ | |
index: | |
this.state.index === this.props.children.length - 1 | |
? 0 | |
: this.state.index + 1 | |
}); | |
}; | |
componentDidMount() { | |
this.interval = setInterval(this.invokeInterval, 5000); | |
} | |
componentWillUnmount() { | |
clearInterval(this.interval); | |
} | |
handlePreviousQuote = () => { | |
this.setState({ index: this.state.index - 1 }); | |
}; | |
handleNextQuote = () => { | |
const interval = this.interval; | |
clearInterval(interval); | |
setTimeout( | |
() => (this.interval = setInterval(this.invokeInterval, 5000)), | |
5000 | |
); | |
this.setState({ index: this.state.index + 1 }); | |
}; | |
render() { | |
return ( | |
<Grid container justify="center" wrap="nowrap"> | |
<Grid item xs={2}> | |
{this.state.index > 0 && ( | |
<ChevronLeft | |
onClick={this.handlePreviousQuote} | |
style={{ cursor: 'pointer', fontSize: 40 }} | |
/> | |
)} | |
</Grid> | |
<Grid item> | |
{ | |
React.Children.map(this.props.children, child => | |
React.cloneElement(child, { | |
index: this.state.index, | |
total: React.Children.count(this.props.children) | |
}) | |
)[this.state.index] | |
} | |
</Grid> | |
<Grid item xs={2}> | |
{this.state.index < this.props.children.length - 1 && ( | |
<ChevronRight | |
onClick={this.handleNextQuote} | |
style={{ cursor: 'pointer', fontSize: 40 }} | |
/> | |
)} | |
</Grid> | |
</Grid> | |
); | |
} | |
} | |
const SliderAuthor = props => ( | |
<> | |
<br /> - {props.children} | |
</> | |
); | |
const SliderItemText = props => <div>"{props.children}"</div>; | |
const SliderItem = props => { | |
return ( | |
<div style={{ opacity: props.index !== props.total ? 1 : 0 }}> | |
{props.children} | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment