Adarsh Sreeram
Adarsh Sreeram

Reputation: 962

How to get and pass the details of the active slide in react native using react-native-snap-carousel

I need to pass the details of the currently active slide to another js file. how can I do this (there are 8 slides)?

The details that I need to pass is the slide's name and Index,

Here is my carousel js file :

import React, { Component } from 'react';
import { Dimensions, View, Image } from 'react-native';
import Carousel from 'react-native-snap-carousel';

const { height, width } = Dimensions.get('window');

class TeamScroll extends Component {

  render() {
    return (
      <View >
      <View style={{ transform: [{ rotate: '-14deg' }] }}>
      <Carousel
      ref={(c) => { this.props.carouselRef = c; }}
      inactiveSlideOpacity={0.6}
      inactiveSlideScale={0.65}
      firstItem={1}
      sliderWidth={width}
      itemWidth={width / 3} >
      <Image
      source={require('./Images/logo-chepauk.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logo-dindigul.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logo-kanchi.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logo-karaikudi.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logo-kovai.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logomadurai.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logothiruvallur.png')}
      style={styles.logoStyle}  />
      <Image
      source={require('./Images/logotuti.png')}
      style={styles.logoStyle}  />
      </Carousel>
      </View>
      </View>
);
}
}
const styles = {
  logoStyle: {
    transform: [{ rotate: '14deg' }],
    width: width / 3,
    height: width / 3
    }
};
export default TeamScroll;

Here is one of the files where I need to use these details

import React, { Component } from 'react';
import { Image, Text, View, TouchableWithoutFeedback, Animated, Dimensions } from 'react-native';
import { Actions } from 'react-native-router-flux';
import TeamScroll from './TeamScroll';

const a = require('./Images/over3_selected.png');
const b = require('./Images/over3.png');
const c = require('./Images/over5_selected.png');
const d = require('./Images/over5.png');
const e = require('./Images/over10_selected.png');
const f = require('./Images/over10.png');

const Sound = require('react-native-sound');

const btnSound = new Sound('btn_sound.mp3', Sound.MAIN_BUNDLE);

const w = Dimensions.get('window').width;
const h = Dimensions.get('window').height;


 class ChallengeScreen extends Component {
   state = {
     threePressed: false,
     fivePressed: false,
     tenPressed: false,
   }
   componentWillMount() {
  this.slide1 = new Animated.Value(0);
  this.slide2 = new Animated.Value(0);
  this.slide3 = new Animated.Value(0);

  this.ball1();
  this.ball2();
  this.ball3();
  }
 ball1() {
 Animated.timing(
 this.slide1, {
 delay: 100,
 toValue: -(w / 2.57),
 duration: 700,
 }
 ).start();
 }

 ball2() {
Animated.timing(
 this.slide2, {
 delay: 200,
 toValue: -(w / 2.25),
duration: 900,
}
 ).start();
}
 ball3() {
 Animated.timing(
   this.slide3, {
 delay: 300,
 toValue: -(w / 2),
 duration: 1100,
 }
 ).start();
 }


  render() {
  return (
<Image
    source={require('./Images/bg_inner.png')} style={styles.backgroundStyle}>

    <Text style={styles.chooseteamtextStyle}>
    CHOOSE YOUR TEAM
    </Text>
    <Image source={require('./Images/team-logo-band.png')} style={styles.band1Style}>
    <TeamScroll carouselRef />
    </Image>

    <Text style={styles.opponentStyle}>
    YOUR OPPONENT
    </Text>
    <Image source={require('./Images/team-logo-band.png')} style={styles.band2Style}>
    <TeamScroll carouselRef />
    </Image>

    <Text style={styles.overstextStyle}>
    OVERS
    </Text>
    <View style={styles.viewStyle}>

     <TouchableWithoutFeedback
     onPress={() => {
       btnSound.play();
       playFunc(3, this.props.challenge); }
     }
     onPressIn={() => {
       this.setState({ threePressed: true });
     }}
     onPressOut={() => {
       this.setState({ threePressed: false });
     }}
     >
    <Animated.Image source={this.state.threePressed ? a : b}
    style={[styles.over3Style, { transform: [{ translateY: this.slide1 }] }]} />
    </ TouchableWithoutFeedback>

    <TouchableWithoutFeedback
    onPress={() => {
      btnSound.play();
      playFunc(5, this.props.challenge); }
    }
    onPressIn={() => {
      this.setState({ fivePressed: true });
    }}
    onPressOut={() => {
      this.setState({ fivePressed: false });
    }}>
    <Animated.Image source={this.state.fivePressed ? c : d}
    style={[styles.over5Style, { transform: [{ translateY: this.slide2 }] }]} />
</ TouchableWithoutFeedback>

    <TouchableWithoutFeedback
    onPress={() => {
      btnSound.play();
      playFunc(10, this.props.challenge); }
    }
    onPressIn={() => {
      this.setState({ tenPressed: true });
    }}
    onPressOut={() => {
      this.setState({ tenPressed: false });
    }}>
    <Animated.Image source={this.state.tenPressed ? e : f}
    style={[styles.over10Style, { transform: [{ translateY: this.slide3 }] }]} />
    </ TouchableWithoutFeedback>

    </View>
</ Image>
);
}
}
function playFunc(num, param) {
if (num === 3 && param === 'Computer') {
  Actions.screen4({ balls: 18 });
  
}
else if (num === 5 && param === 'Computer') {
  Actions.screen4({ balls: 30 });
}
else if (num === 10 && param === 'Computer') {
  Actions.screen4({ balls: 60 });
}
else if (num === 3 && param === 'Team') {
  Actions.screen3({ balls: 18 });
}
else if (num === 5 && param === 'Team') {
  Actions.screen3({ balls: 30 });
  }
else if (num === 10 && param === 'Team') {
  Actions.screen3({ balls: 60 });
}
}
const styles = {
  viewStyle: {

    flexDirection: 'row',
    justifyContent: 'flex-start'
  },
backgroundStyle: {
   flex: 1,
   width: w,
   height: h,
   flexWrap: 'wrap',

 },
 chooseteamtextStyle: {
 textAlign: 'center',
   marginTop: h / 6.57,
   fontSize: 22,
   color: 'white',
   fontFamily: 'Switzerland-Cond-Black-Italic',
   transform: [{ rotate: '-14deg' }]
 },
 band1Style: {
resizeMode: 'stretch',
width: (w / 0.947),
height: (h / 3.93),
 },
 opponentStyle: {
   textAlign: 'center',
   marginTop: -(h / 59.2),
   fontSize: 22,
   color: 'white',
   fontFamily: 'Switzerland-Cond-Black-Italic',
   transform: [{ rotate: '-15deg' }]
 },
 band2Style: {
resizeMode: 'stretch',
width: (w / 0.947),
height: (h / 4),
 },
 overstextStyle: {
   textAlign: 'center',
   bottom: (h / 59.2),
   fontSize: 22,
   color: 'white',
   fontFamily: 'Switzerland-Cond-Black-Italic',
   transform: [{ rotate: '-15deg' }]
 },
 over3Style: {
   flexDirection: 'row',
alignItems: 'flex-start',
width: (w / 4.5),
height: (h / 7.4),
top: (h / 3.482),
left: (w / 5.142),
 },
 over5Style: {
   flexDirection: 'row',
alignItems: 'center',
width: (w / 4.5),
height: (h / 7.4),
bottom: -(h / 3.48),
left: (h / 8.45)
 },
 over10Style: {
   flexDirection: 'row',
alignItems: 'flex-end',
width: (w / 4.5),
height: (h / 7.4),
 top: (h / 3.48),
right: -(w / 5.42)
 }
 };
export default ChallengeScreen;

I have tried using state and props for doing it, and also using getters like currentIndex using carousel's reference but couldn't get the details

Upvotes: 1

Views: 6763

Answers (2)

Fabio Crisci
Fabio Crisci

Reputation: 1195

I'm using this

class TeamScroll extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentIndex: 0,
    };
  }

  changePage(nextIndex, isLast) {
    this.setState({ currentIndex: nextIndex });
    this.props.onChangePage(nextIndex + 1, isLast);
  }

  render() {
    return (
      <Page>
        <Carousel
          ref={(carousel) => { this.carousel = carousel; }}
          firstItem={this.state.currentIndex}
          onSnapToItem={(index) => this.changePage(index, index === screens.length - 1)}
          data={screens}
          renderItem={this.renderCarouselItem}
        />
    );
  }
}

Note that I'm using the new syntax introduced in version 3, but it works as well in version 2.

The class has onChangePage prop that gets called when you snap to another item.

You can use the onChangePage with

<TeamScroll onChangePage={(pageIndex, isLastPage) => {
   // do something here, maybe
   this.setState({ currentPage: pageIndex });
}} />

Upvotes: 1

bend
bend

Reputation: 1404

What about adding a dedicated prop to <TeamScroll />?

TeamScroll.js

class TeamScroll extends Component {

    static propTypes = {
        snapCallback: PropTypes.func
    }

    static defaultProps = {
        snapCallback: () => {}
    }

    constructor (props) {
        super(props);
        this._onSnapToItem = this._onSnapToItem.bind(this);
    }

    _onSnapToItem (index) {
        this.props.snapCallback(index, this.state.customData);
    }

    render() {
        return (
            <View >
                <View style={{ transform: [{ rotate: '-14deg' }] }}>
                    <Carousel onSnapToItem={this._onSnapToItem}>
                        // images
                    </Carousel>
                </View>
            </View>
        );
    }
}

ChallengeScreen.js

class ChallengeScreen extends Component {

    onSnap (index, data) {
        console.log('CAROUSEL INDEX', { index, data });
    }

    render() {
        return (
            <Image source={require('./Images/team-logo-band.png')} style={styles.band2Style}>
                <TeamScroll carouselRef snapCallback={onSnap} />
            </Image>
        );
    }
}

Upvotes: 1

Related Questions