### Install react-native-snap-carousel
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
Install the core package using npm.
```bash
$ npm install --save react-native-snap-carousel
```
--------------------------------
### Install Typescript Definitions
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
If using Typescript, install the necessary type definitions.
```bash
$ npm install --save @types/react-native-snap-carousel
```
--------------------------------
### Stack Layout Example
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Implement the 'stack' layout for a stacked item effect. This layout offers a different visual presentation compared to the default.
```javascript
```
--------------------------------
### ParallaxImage Usage Example
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PARALLAX_IMAGE.md
Demonstrates how to integrate the ParallaxImage component within a carousel. Ensure `hasParallaxImages` is set to true on the Carousel component and pass the `parallaxProps` to ParallaxImage.
```javascript
import Carousel, { ParallaxImage } from 'react-native-snap-carousel';
import { Dimensions, StyleSheet } from 'react-native';
const { width: screenWidth } = Dimensions.get('window')
export default class MyCarousel extends Component {
_renderItem ({item, index}, parallaxProps) {
return (
{ item.title }
);
}
render () {
return (
);
}
}
const styles = StyleSheet.create({
item: {
width: screenWidth - 60,
height: screenWidth - 60,
},
imageContainer: {
flex: 1,
marginBottom: Platform.select({ ios: 0, android: 1 }), // Prevent a random Android rendering issue
backgroundColor: 'white',
borderRadius: 8,
},
image: {
...StyleSheet.absoluteFillObject,
resizeMode: 'cover',
},
})
```
--------------------------------
### React Hooks Carousel with Parallax Images
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PARALLAX_IMAGE.md
This snippet shows a complete example of a carousel component using React Hooks and the ParallaxImage component from react-native-snap-carousel. It includes setup for data, a carousel ref, and a function to navigate to the next slide. Use this for implementing dynamic carousels with image effects in React Native applications.
```javascript
import React, {useRef, useState, useEffect} from 'react';
import Carousel, {ParallaxImage} from 'react-native-snap-carousel';
import {
View,
Text,
Dimensions,
StyleSheet,
TouchableOpacity,
Platform,
} from 'react-native';
const ENTRIES1 = [
{
title: 'Beautiful and dramatic Antelope Canyon',
subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
illustration: 'https://i.imgur.com/UYiroysl.jpg',
},
{
title: 'Earlier this morning, NYC',
subtitle: 'Lorem ipsum dolor sit amet',
illustration: 'https://i.imgur.com/UPrs1EWl.jpg',
},
{
title: 'White Pocket Sunset',
subtitle: 'Lorem ipsum dolor sit amet et nuncat ',
illustration: 'https://i.imgur.com/MABUbpDl.jpg',
},
{
title: 'Acrocorinth, Greece',
subtitle: 'Lorem ipsum dolor sit amet et nuncat mergitur',
illustration: 'https://i.imgur.com/KZsmUi2l.jpg',
},
{
title: 'The lone tree, majestic landscape of New Zealand',
subtitle: 'Lorem ipsum dolor sit amet',
illustration: 'https://i.imgur.com/2nCt3Sbl.jpg',
},
];
const {width: screenWidth} = Dimensions.get('window');
const MyCarousel = props => {
const [entries, setEntries] = useState([]);
const carouselRef = useRef(null);
const goForward = () => {
carouselRef.current.snapToNext();
};
useEffect(() => {
setEntries(ENTRIES1);
}, []);
const renderItem = ({item, index}, parallaxProps) => {
return (
{item.title}
);
};
return (
go to next slide
);
};
export default MyCarousel;
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
width: screenWidth - 60,
height: screenWidth - 60,
},
imageContainer: {
flex: 1,
marginBottom: Platform.select({ios: 0, android: 1}), // Prevent a random Android rendering issue
backgroundColor: 'white',
borderRadius: 8,
},
image: {
...StyleSheet.absoluteFillObject,
resizeMode: 'cover',
},
});
```
--------------------------------
### Tinder Layout Example
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Utilize the 'tinder' layout for a Tinder-like card swiping animation. This layout is suitable for interactive card-based interfaces.
```javascript
```
--------------------------------
### Configure Slide Margins and Width
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Set up horizontal margins between slides and ensure itemWidth includes this margin. This example demonstrates calculating dimensions and applying styles for slide containers.
```javascript
const horizontalMargin = 20;
const slideWidth = 280;
const sliderWidth = Dimensions.get('window').width;
const itemWidth = slideWidth + horizontalMargin * 2;
const itemHeight = 200;
const styles = StyleSheet.create({
slide: {
width: itemWidth,
height: itemHeight,
paddingHorizontal: horizontalMargin
// other styles for the item container
},
slideInnerContainer: {
width: slideWidth,
flex: 1
// other styles for the inner container
}
};
```
--------------------------------
### Carousel Component Setup
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Configure the Carousel component with data, item rendering function, and dimensions. Ensure the renderItem function is bound to the component's context to access navigation props.
```javascript
```
--------------------------------
### Accessing Carousel Instance via Callback Ref
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Recommended method to get a reference to the carousel instance using a callback attribute. This reference can then be used to call carousel methods.
```javascript
{ this._carousel = c; }}
/>
// methods can then be called this way
onPress={() => { this._carousel.snapToNext(); }}
```
--------------------------------
### Accessing Carousel Instance via String Ref (Legacy)
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Legacy method to get a reference to the carousel instance using a string attribute. This reference can then be used to call carousel methods.
```javascript
// methods can then be called this way
onPress={() => { this.refs.carousel.snapToNext(); }}
```
--------------------------------
### Defining Opacity Animation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Animates the opacity of carousel items. This example creates a fade-out effect between the second and third items.
```javascript
opacity: animatedValue.interpolate({
inputRange: [2, 3],
outputRange: [1, 0]
})
```
--------------------------------
### Carousel Getters
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Access properties of the carousel instance to get its current state, such as the active item index or scroll position.
```APIDOC
## Carousel Getters
To use these getters, you need a reference to the carousel's instance.
### Properties
- **`currentIndex`** (int) - Required - The index of the currently active item. Starts at 0.
- **`currentScrollPosition`** (int) - Required - The current content offset of the underlying `ScrollView`. Starts at 0 if `activeSlideAlignment` is set to `start`, otherwise it can be a negative value.
```
--------------------------------
### Handle Device Rotation with Carousel Layout
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Update carousel dimensions on layout changes to ensure proper re-centering after device rotation. This example demonstrates how to capture viewport dimensions and apply them to the carousel's sliderWidth and itemWidth.
```javascript
constructor(props) {
super(props);
this.state = {
viewport: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
};
}
render() {
return (
{
this.setState({
viewport: {
width: Dimensions.get('window').width,
height: Dimensions.get('window').height
}
});
}}
>
{ this.carousel = c; } }
sliderWidth={this.state.viewport.width}
itemWidth={this.state.viewport.width}
...
/>
);
}
```
--------------------------------
### Slide Interpolated Style Function Example
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
The `slideInterpolatedStyle` prop is a function that returns a style object. It uses the animated value to interpolate styles like opacity, allowing for custom item animations based on scroll position. Using `extrapolate: 'clamp'` is recommended to keep values within the defined output range.
```javascript
function animatedStyle = (index, animatedValue, carouselProps) => {
return {
opacity: animatedValue.interpolate({
inputRange: [-1, 0, 1],
outputRange: [0, 1, 0.5],
extrapolate: 'clamp'
})
}
}
```
--------------------------------
### Try the latest commits
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
For those who want to test the most recent changes, you can try the latest commits from the development branch.
```link
https://stackoverflow.com/a/27630247/
```
--------------------------------
### View available beta versions
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
Use this command to check the latest beta versions of react-native-snap-carousel available on npm.
```bash
npm view react-native-snap-carousel versions --json
```
--------------------------------
### Follow the development PR
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
Monitor the progress and discussions for the new version by following the specified pull request on GitHub.
```link
https://github.com/meliorence/react-native-snap-carousel/pull/678
```
--------------------------------
### Carousel Methods
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
This section details the methods available on the Carousel component instance. To use these methods, you need to obtain a reference to the carousel component, either by using a callback attribute (recommended) or a string attribute (legacy).
```APIDOC
## Carousel Methods
### Description
Provides programmatic control over the carousel's behavior, including autoplay and item snapping.
### Reference to the component
To use these methods, you need to create a reference to the carousel's instance.
#### ref as a callback attribute (**recommended**)
```javascript
{ this._carousel = c; }}
/>
// methods can then be called this way
onPress={() => { this._carousel.snapToNext(); }}
```
#### ref as a string attribute ([legacy](http://stackoverflow.com/questions/37468913/why-ref-string-is-legacy))
```javascript
// methods can then be called this way
onPress={() => { this.refs.carousel.snapToNext(); }}
```
### Available methods
Method | Description
------ | ------
`startAutoplay (instantly = false)` | Start the autoplay programmatically
`stopAutoplay ()` | Stop the autoplay programmatically
`snapToItem (index, animated = true, fireCallback = true)` | Snap to an item programmatically
`snapToNext (animated = true, fireCallback = true)` | Snap to next item programmatically
`snapToPrev (animated = true, fireCallback = true)` | Snap to previous item programmatically
`triggerRenderingHack (offset)` | Call this when needed to work around [a random `FlatList` bug](https://github.com/facebook/react-native/issues/1831) that keeps content hidden until the carousel is scrolled (see [#238](https://github.com/meliorence/react-native-snap-carousel/issues/238)). Note that the `offset` parameter is not required and will default to either `1` or `-1` depending on the current scroll position.
```
--------------------------------
### Implement Fullscreen Slides
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Create fullscreen slides by setting the carousel's `sliderWidth`, `itemWidth`, and `slideStyle` to match the viewport dimensions. Ensure `inactiveSlideOpacity` and `inactiveSlideScale` are set to 1 for a consistent fullscreen effect.
```javascript
const { width: viewportWidth, height: viewportHeight } = Dimensions.get('window');
export class MyCarousel extends Component {
_renderItem ({item, index}) {
return (
// or { flex: 1 } for responsive height
);
}
render () {
return (
);
}
}
```
--------------------------------
### Basic Pagination Usage with Carousel
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PAGINATION.md
Connects the Pagination component to a Carousel component and demonstrates basic customization of active and inactive dots. Ensure you import both Carousel and Pagination.
```javascript
import Carousel, { Pagination } from 'react-native-snap-carousel';
export default class MyCarousel extends Component {
_renderItem ({item, index}) {
return
}
get pagination () {
const { entries, activeSlide } = this.state;
return (
);
}
render () {
return (
this.setState({ activeSlide: index }) }
/>
{ this.pagination }
);
}
}
```
--------------------------------
### New Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
Details on new props introduced in version 4.0.0, including `useExperimentalSnap` for alternative item centering and `onScrollIndexChanged` for real-time active slide index updates.
```APIDOC
## New Props
### `useExperimentalSnap`
**Description**: Allows for an alternative centering option that avoids white spaces at the beginning/end of the carousel. Note that with this enabled, some items might not be fully "reachable" (snap callbacks and animations may not complete for the last item(s)). It's recommended to use this only if `onSnapToItem` is not critical and `inactiveSlideScale` and `inactiveSlideOpacity` are both set to `1`. A side effect is the ability to slide only one item at a time when `disableIntervalMomentum` is true.
**Type**: Boolean
**Default**: `false`
### `onScrollIndexChanged(slideIndex)`
**Description**: Callback executed as soon as the active index changes during a scroll. This differs from `onSnapToItem`, which is only triggered for the final active item. **Caution**: Avoid heavy computations or rendering within this callback.
**Type**: Function
**Default**: `undefined`
```
--------------------------------
### Basic Carousel Implementation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
A basic implementation of a React Native Snap Carousel component. Ensure you have defined 'entries', 'sliderWidth', and 'itemWidth' in your component's state or props.
```javascript
import Carousel from 'react-native-snap-carousel';
export class MyCarousel extends Component {
_renderItem = ({item, index}) => {
return (
{ item.title }
);
}
render () {
return (
{ this._carousel = c; }}
data={this.state.entries}
renderItem={this._renderItem}
sliderWidth={sliderWidth}
itemWidth={itemWidth}
/>
);
}
}
```
--------------------------------
### Reduce rerenders with why-did-you-render
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
This snippet suggests using the `why-did-you-render` library to help identify and reduce unnecessary component rerenders in your React Native application.
```bash
npm install --save-dev why-did-you-render
```
--------------------------------
### Updated Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
Information on updated props in version 4.0.0, specifically the `renderItem` prop which now includes a `dataIndex` parameter.
```APIDOC
## Updated Props
### `renderItem({ item, index, dataIndex })`
**Description**: The `renderItem` function now includes an additional parameter, `dataIndex`. This `dataIndex` represents the index based on your original data set, not the internal carousel item count. This is particularly useful for looped carousels where these indices might differ, allowing you to reference your data accurately.
**Type**: Function
**Default**: **Required**
```
--------------------------------
### Full Custom Carousel Implementation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Combines scroll interpolator and animated styles for a fully custom carousel animation. Requires importing Carousel and getInputRangeFromIndexes.
```javascript
import React, { PureComponent } from 'react';
import Carousel, { getInputRangeFromIndexes } from 'react-native-snap-carousel';
export default class MyCustomCarousel extends PureComponent {
_scrollInterpolator (index, carouselProps) {
const range = [3, 2, 1, 0, -1];
const inputRange = getInputRangeFromIndexes(range, index, carouselProps);
const outputRange = range;
return { inputRange, outputRange };
}
_animatedStyles (index, animatedValue, carouselProps) {
const sizeRef = carouselProps.vertical ? carouselProps.itemHeight : carouselProps.itemWidth;
const translateProp = carouselProps.vertical ? 'translateY' : 'translateX';
return {
zIndex: carouselProps.data.length - index,
opacity: animatedValue.interpolate({
inputRange: [2, 3],
outputRange: [1, 0]
}),
transform: [{
rotate: animatedValue.interpolate({
inputRange: [-1, 0, 1, 2, 3],
outputRange: ['-25deg', '0deg', '-3deg', '1.8deg', '0deg'],
extrapolate: 'clamp'
})
}, {
[translateProp]: animatedValue.interpolate({
inputRange: [-1, 0, 1, 2, 3],
outputRange: [
-sizeRef * 0.5,
0,
-sizeRef, // centered
-sizeRef * 2, // centered
-sizeRef * 3 // centered
],
extrapolate: 'clamp'
})
}]
};
}
render () {
return (
);
}
}
```
--------------------------------
### Render Item Function
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
The _renderItem function is responsible for rendering each slide. It receives item and index as arguments and should pass necessary props, such as navigation, to the slide entry component.
```javascript
_renderItem ({item, index}) {
return (
);
}
```
--------------------------------
### Stack Carousel Layout
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
Implement the 'stack' layout for a card-stack effect. Adjust 'layoutCardOffset' to control the card spacing. Note potential Android-specific visual inversions.
```javascript
```
--------------------------------
### Migrate Carousel Slides from Children to Data/RenderItem
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Convert carousel slides from direct children to using the `data` and `renderItem` props, similar to React Native's FlatList. The `key` prop is no longer needed for items.
```javascript
get slides () {
return this.state.entries.map((entry, index) => {
return (
{ entry.title }
);
});
}
render () {
return (
{ this.slides }
);
}
```
```javascript
_renderItem ({item, index}) {
return (
{ item.title }
);
}
render () {
return (
);
}
```
--------------------------------
### Enable Dynamic Item Height
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
To achieve dynamic item heights that fill available space, apply `{ flex: 1 }` to all relevant wrapper components, including the carousel's `containerCustomStyle` and `slideStyle`.
```javascript
_renderItem ({item, index}) {
return (
);
}
render () {
return (
);
}
```
--------------------------------
### Use Specific Commit in package.json
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Specify a GitHub commit directly in your package.json to use a version not yet published to npm. This is useful for testing unreleased features or bug fixes.
```javascript
"react-native-snap-carousel": "https://github.com/meliorence/react-native-snap-carousel#fbdb671"
```
--------------------------------
### Android zIndex Workaround with Elevation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
This snippet demonstrates using the Android-specific 'elevation' prop as a workaround for zIndex issues on Android. It's suitable when user interaction is not a primary concern, as it doesn't affect the rendering hierarchy for tap events.
```javascript
{ elevation: carouselProps.data.length - index }
```
--------------------------------
### Carousel Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
These are the essential props required to configure and render the carousel. They define the data source, item rendering logic, and dimensions for both the carousel and its items.
```APIDOC
## Carousel Props
### Description
Configuration options for the React Native Snap Carousel component.
### Props
#### Required Props
- **`data`** (Array) - Required - Array of items to loop on.
- **`renderItem`** (Function) - Required - Function that takes an item from `data` and renders it. Receives `{item, index}` and must return a React element.
- **`itemWidth`** (Number) - Required for horizontal carousel - Width in pixels of carousel's items. Must be the same for all items.
- **`sliderWidth`** (Number) - Required for horizontal carousel - Width in pixels of the carousel itself.
- **`itemHeight`** (Number) - Required for vertical carousel - Height in pixels of carousel's items. Must be the same for all items.
- **`sliderHeight`** (Number) - Required for vertical carousel - Height in pixels of the carousel itself.
```
--------------------------------
### Autoplay Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Configure and control the autoplay behavior of the carousel. These props allow you to trigger autoplay, set delays, and define the interval between automatic item transitions.
```APIDOC
## Autoplay
### Description
Configure and control the autoplay behavior of the carousel.
### Props
- **autoplay** (Boolean) - Optional - Trigger autoplay on mount. If you enable autoplay, we recommend you to set `enableMomentum` to `false` (default) and `lockScrollWhileSnapping` to `true`; this will enhance user experience a bit.
- **autoplayDelay** (Number) - Optional - Delay before enabling autoplay on startup & after releasing the touch.
- **autoplayInterval** (Number) - Optional - Delay in ms until navigating to the next item.
```
--------------------------------
### Carousel Loop Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Props specifically for enabling and configuring the infinite loop mode of the carousel.
```APIDOC
## Carousel Loop Props
### Description
Configure the infinite loop mode for the carousel.
### Props
- **`loop`** (Boolean) - Optional - Enable infinite loop mode. Requires `enableSnap` to be set to `true`. Default: `false`
- **`loopClonesPerSide`** (Number) - Optional - Number of clones to append to each side of the original items for smoother looping. Increasing this improves user experience at the cost of memory. Default: `3`
```
--------------------------------
### Tinder Carousel Layout
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
Utilize the 'tinder' layout for a Tinder-like swipe animation. The 'layoutCardOffset' prop can be used to fine-tune the card offset. Be aware of potential Android-specific visual inversions.
```javascript
```
--------------------------------
### Slider Entry Component
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
The SliderEntry component displays individual slide content. It receives data and navigation props, allowing navigation to a different screen when a slide is pressed.
```javascript
export default class SliderEntry extends Component {
static propTypes = {
data: PropTypes.object.isRequired,
};
render () {
const { data: { title, subtitle, illustration}, navigation } = this.props; //<------
return (
navigation.navigate('Feed')} //<------- now you can use navigation
>
}
```
--------------------------------
### Configuring Translation Animation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Handles the translation animation for carousel items, ensuring they are centered and accounting for horizontal/vertical layouts. Item -1 moves slightly faster.
```javascript
const sizeRef = carouselProps.vertical ? carouselProps.itemHeight : carouselProps.itemWidth;
const translateProp = carouselProps.vertical ? 'translateY' : 'translateX';
return {
transform: [{
[translateProp]: animatedValue.interpolate({
inputRange: [-1, 0, 1, 2, 3],
outputRange: [
-sizeRef * 0.5,
0,
-sizeRef, // centered
-sizeRef * 2, // centered
-sizeRef * 3 // centered
],
extrapolate: 'clamp'
})
}]
};
```
--------------------------------
### Scroll Interpolator Function Structure
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
The `scrollInterpolator` prop must be a function that returns an object defining the inputRange and outputRange for scroll position interpolation. Both arrays must have the same length.
```javascript
{
inputRange: [scroll value 1, scroll value 2, ...],
outputRange: [value associated with 1, value associated with 2, ...],
}
```
--------------------------------
### Callback Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Event handlers that are triggered by carousel interactions. These include callbacks for layout changes, scrolling events, and item snapping.
```APIDOC
## Callbacks
### Description
Event handlers that are triggered by carousel interactions.
### Props
- **onLayout(event)** (Function) - Optional - Exposed `View` callback; invoked on mount and layout changes.
- **onScroll(event)** (Function) - Optional - Exposed `ScrollView` callback; fired while scrolling.
- **onBeforeSnapToItem(slideIndex)** (Function) - Optional - Callback fired when the new active item has been determined, before snapping to it.
- **onSnapToItem(slideIndex)** (Function) - Optional - Callback fired after snapping to an item.
```
--------------------------------
### Style and Animation Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
Customize the visual appearance and animation of carousel items. This includes options for custom animations, active slide alignment, styling for containers, and effects for inactive slides.
```APIDOC
## Style and Animation
### Description
Customize the visual appearance and animation of carousel items.
### Props
- **activeAnimationOptions** (Object) - Optional - Custom animation options. Note that `useNativeDriver` will be enabled by default and that opacity's easing will always be kept linear. Setting this prop to something other than `null` will trigger custom animations and will completely change the way items are animated: rather than having their opacity and scale interpolated based the scroll value (default behavior), they will now play the custom animation you provide as soon as they become active. This means you cannot use props `layout`, `scrollInterpolator` or `slideInterpolatedStyle` in conjunction with `activeAnimationOptions`.
- **activeAnimationType** (String) - Optional - Custom [animation type](https://facebook.github.io/react-native/docs/animated.html#configuring-animations): either `'decay`, `'spring'` or `'timing'`. Note that it will only be applied to the scale animation since opacity's animation type will always be set to `timing` (no one wants the opacity to 'bounce' around).
- **activeSlideAlignment** (String) - Optional - Determine active slide's alignment relative to the carousel. Possible values are: `'start'`, `'center'` and `'end'`. It is not recommended to use this prop in conjunction with the `layout` one.
- **containerCustomStyle** (View Style Object) - Optional - Optional styles for Scrollview's global wrapper.
- **contentContainerCustomStyle** (View Style Object) - Optional - Optional styles for Scrollview's items container.
- **inactiveSlideOpacity** (Number) - Optional - Value of the opacity effect applied to inactive slides.
- **inactiveSlideScale** (Number) - Optional - Value of the 'scale' transform applied to inactive slides.
- **inactiveSlideShift** (Number) - Optional - Value of the 'translate' transform applied to inactive slides (see [#204](https://github.com/meliorence/react-native-snap-carousel/issues/204) or [the "custom interpolations" doc](https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md) for an example usage). This prop will have no effect with layouts others than the default one.
- **layout** (String) - Optional - Define the way items are rendered and animated. Possible values are `'default'`, `'stack'` and `'tinder'`. See [this](https://github.com/meliorence/react-native-snap-carousel#layouts-and-custom-interpolations) for more info and visual examples. :warning: Setting this prop to either `'stack'` or `'tinder'` will activate `useScrollView` [to prevent rendering bugs with `FlatList`](https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md#caveats). Therefore, those layouts won't be suited if you have a large data set since all items are going to be rendered upfront.
- **layoutCardOffset** (Number) - Optional - Use to increase or decrease the default card offset in both 'stack' and 'tinder' layouts.
- **scrollInterpolator** (Function) - Optional - Used to define custom interpolations. See [the dedicated doc](https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md#summary).
- **slideInterpolatedStyle** (Function) - Optional - Used to define custom interpolations. See [the dedicated doc](https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md#summary).
- **slideStyle** (Animated View Style Object) - Optional - Optional style for each item's container (the one whose scale and opacity are animated).
```
--------------------------------
### Setting zIndex for Active Item
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Ensures the active item sits on top of others by inverting the default zIndex behavior. Be aware this may cause swipe/click events to be missed.
```javascript
{
zIndex: carouselProps.data.length - index
}
```
--------------------------------
### Default Carousel Layout
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/README.md
Use the 'default' layout for a standard carousel appearance. No additional offset properties are needed.
```javascript
```
--------------------------------
### Removed Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/VERSION_4.md
A list of props that have been removed in version 4.0.0 of the carousel.
```APIDOC
## Removed Props
- `activeAnimationOptions`
- `activeAnimationType`
- `enableMomentum`
- `lockScrollTimeoutDuration`
- `lockScrollWhileSnapping`
- `onBeforeSnapToItem`
- `swipeThreshold`
```
--------------------------------
### Render Custom Carousel Items
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Define a renderItem function to customize how each slide is displayed. This function receives item data and index, and should return a React element representing the slide.
```javascript
_renderItem ({item, index}) {
return (
);
}
render () {
return (
);
}
```
--------------------------------
### Render Different Slide Types Based on Data
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Use the `renderItem` function to conditionally render different components based on the `type` property of each item in your data array. This allows for heterogeneous carousel content.
```javascript
_renderItem ({item, index}) {
if (item.type === 'text') {
return ;
} else if (item.type === 'image') {
return ;
} else {
return ;
}
}
```
--------------------------------
### Set Carousel Container Height
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/TIPS_AND_TRICKS.md
Prevent the carousel container from stretching to fill available space by setting `flexGrow` to 0 in `containerCustomStyle`. Alternatively, provide a fixed height or wrap the carousel in a View with a fixed height.
```javascript
render () {
return (
);
}
```
--------------------------------
### Carousel Behavior Props
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/PROPS_METHODS_AND_GETTERS.md
These props control the fundamental behavior of the carousel, such as scrolling, snapping, and item activation.
```APIDOC
## Carousel Behavior Props
### Description
Controls the core behavior of the carousel, including scrolling, snapping, and item activation.
### Props
- **`activeSlideOffset`** (Number) - Optional - From slider's center, minimum slide distance to be scrolled before being set to active. Default: `20`
- **`apparitionDelay`** (Number) - Optional - Controls the delay during which the carousel will be hidden when mounted to avoid initial flickers. WARNING: on Android, using it may lead to rendering issues. Default: `0`
- **`callbackOffsetMargin`** (Number) - Optional - Defines a small margin to increase the "sweet spot's" width for more reliable scroll event callbacks, especially on Android. Default: `5`
- **`enableMomentum`** (Boolean) - Optional - Enables momentum scrolling. Default: `false`
- **`enableSnap`** (Boolean) - Optional - If enabled, releasing the touch will scroll to the center of the nearest/active item. Default: `true`
- **`firstItem`** (Number) - Optional - Index of the first item to display. Ensure `getItemLayout` & `initialScrollIndex` are used if this prop doesn't work as expected. Default: `0`
- **`hasParallaxImages`** (Boolean) - Optional - Set to true if the carousel contains `` components. Required for passing specific data to children. Default: `false`
- **`lockScrollTimeoutDuration`** (Number) - Optional - Timer duration to release scroll if issues occur with regular callback handling when `lockScrollWhileSnapping` is enabled. Normally not needed. Default: `1000`
- **`lockScrollWhileSnapping`** (Boolean) - Optional - Prevents user swiping while the carousel is snapping to a position. Note: has no effect if `enableMomentum` is `true`. Default: `false`
- **`scrollEnabled`** (Boolean) - Optional - When `false`, the view cannot be scrolled via touch interaction. Default: `true`
- **`shouldOptimizeUpdates`** (Boolean) - Optional - Implements a `shouldComponentUpdate` strategy to minimize updates. Default: `true`
- **`swipeThreshold`** (Number) - Optional - Delta x when swiping to trigger the snap. Default: `20`
- **`useScrollView`** (Boolean) - Optional - Whether to use a `ScrollView` component instead of `FlatList`. Recommended for small sets of slides and thorough performance testing. Default: `false` for `default` layout, `true` for `stack` and `tinder` layouts.
- **`vertical`** (Boolean) - Optional - Layout slides vertically instead of horizontally. Default: `false`
```
--------------------------------
### Define Custom Scroll Interpolator
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Use this function to define custom scroll interpolations for advanced animations. It requires the item's index and carousel properties. Ensure the range is declared in reverse order.
```javascript
import { getInputRangeFromIndexes } from 'react-native-snap-carousel';
function scrollInterpolator (index, carouselProps) {
const range = [3, 2, 1, 0, -1]; // <- Remember that this has to be declared in a reverse order
const inputRange = getInputRangeFromIndexes(range, index, carouselProps);
const outputRange = range;
return { inputRange, outputRange };
}
```
--------------------------------
### Implementing Rotate Animation
Source: https://github.com/meliorence/react-native-snap-carousel/blob/master/doc/CUSTOM_INTERPOLATIONS.md
Applies a rotation animation to carousel items for visual effects. The active and third items are not rotated, while the previous one is rotated negatively.
```javascript
transform: [{
rotate: animatedValue.interpolate({
inputRange: [-1, 0, 1, 2, 3], // <- Unlike with `scrollInterpolator()`, this is declared in a regular order
outputRange: ['-25deg', '0deg', '-3deg', '1.8deg', '0deg'],
extrapolate: 'clamp'
})
}]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.