Last active
January 20, 2019 23:21
-
-
Save JoshBarr/f302ebf7f43ea596ad6a to your computer and use it in GitHub Desktop.
Flickity React integration
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 React from 'react'; | |
import Flickity from 'flickity'; | |
export default React.createClass({ | |
getInitialState() { | |
return { | |
selectedIndex: 0 | |
} | |
}, | |
componentDidMount() { | |
const carousel = this.refs.carousel.getDOMNode(); | |
const options = { | |
cellSelector: '.card', | |
contain: true, | |
initialIndex: 0, | |
accessibility: true | |
} | |
this.flkty = new Flickity(carousel, options); | |
this.flkty.on('cellSelect', this.updateSelected); | |
}, | |
updateSelected() { | |
var index = this.flkty.selectedIndex; | |
this.setState({ | |
selectedIndex: index | |
}); | |
}, | |
componentWillUnmount() { | |
if (this.flkty) { | |
this.flkty.off('cellSelect', this.updateSelected); | |
this.flkty.destroy(); | |
} | |
}, | |
render() { | |
return ( | |
<div ref='carousel' className='carousel'> | |
<div className='card'>1</div> | |
<div className='card'>2</div> | |
<div className='card'>3</div> | |
<div className='card'>4</div> | |
</div> | |
); | |
} | |
} |
@Ajar-Ajar window does not exists on server-side (initially)
If you want to get around this, you'll have to require()
flickity, where you need it, rather than importing it :)
Use this;
Helper:
export function onlyClient(callback) {
if (typeof window !== 'undefined') {
callback();
}
}
Using: onlyClient(() => {
....
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi!
Thank you for sharing!
I'm trying to use this integration in an isomorphic app which renders react also on the server and get the following error:
Do you have any idea how to solve this issue?
Cheers
Ajar