Created
December 29, 2016 20:08
-
-
Save alaingalvan/c7bbd9a2d937b21d6d8b8e21464f982f to your computer and use it in GitHub Desktop.
A TypedScript Carousel Component for React.
This file contains 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 * as React from 'react'; | |
export default class Carousel extends React.Component<any, { index: number }> { | |
private delayHandle; | |
static defaultProps = { | |
delay: 10000, | |
pause: false | |
} | |
constructor(props) { | |
super(props); | |
this.state = { index: 0 }; | |
} | |
componentWillMount() { | |
this.delayHandle = setInterval(() => { | |
var index = (this.props.pause) ? this.state.index : (this.state.index + 1) % this.props.children.length; | |
this.setState({ index: index }); | |
}, this.props.delay); | |
} | |
componentWillUnmount() { | |
clearInterval(this.delayHandle); | |
} | |
render() { | |
if (!this.props.children) { | |
return null; | |
} | |
const styles = { | |
outer: { | |
width: '100vw', | |
height: '100vh', | |
overflow: 'hidden', | |
zIndex: -1, | |
position: 'absolute', | |
left: 0, | |
top: 0 | |
}, | |
mid: { | |
width: `${this.props.children.length}00vw`, | |
height: '100vh', | |
zIndex: '-1', | |
}, | |
inner: { | |
transition: 'transform 1s', | |
transform: `translateX(-${this.state.index}00vw)` | |
}, | |
child: { | |
width: '100vw', | |
height: '100vh', | |
float: 'left', | |
overflow: 'hidden' | |
} | |
}; | |
return ( | |
<div style={styles.outer}> | |
<div style={styles.mid}> | |
<div style={styles.inner}> | |
{this.props.children.map((child, i) => { | |
return ( | |
<div key={i} style={styles.child}> | |
{child} | |
</div> | |
); | |
}) } | |
</div> | |
</div> | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment