Search code examples
react-nativescreenshot

How to get ref in flat list item onpress?


I am trying to capture screen with react-native-view-shot. On press this.refs.viewShot.capture showing undefined.

Here is my code

Flat list code:

<FlatList
                  ref={(list) => this.myFlatList = list}
                  data={this.state.newsListArray}
                  keyExtractor={this._keyExtractor}
                  renderItem={this.renderRowItem}
                />

render on press link:

<TouchableOpacity onPress={ () => {
                Platform.OS === 'ios' ?
                this._captureScreenIos('5c63f7307518134a2aa288ce') :
                this._captureScreenAndroid('5c63f7307518134a2aa288ce')
              }}>
                <View style={{flexDirection:'row'}}>
                  <Icon name="share-alt" size={16} color="#ffb6cf" />
                  <Text style={{paddingLeft:6,fontSize:12,fontWeight:'500'}}>Share News</Text>
                </View>
              </TouchableOpacity>

And that's the function:

_captureScreenIos = (refId) => {
    console.log("Clicked for IOS");
    this.changeLoaderStatus();
    var thisFun = this;
    var viewShotRef = 'viewShot-5c63f7307518134a2aa288ce';
     this.myFlatList.viewShot.capture({width: 2048 / PixelRatio.get(), height: 2048 / PixelRatio.get()}).then(res => {
       RNFetchBlob.fs.readFile(res, 'base64').then((base64data) => {
         console.log("base64data",base64data)
         let base64Image = `data:image/jpeg;base64,${base64data}`;
         const shareOptions = {
           title: "My Beauty Squad",
           //message: "Download my beauty squad with below link."+ "\n" + "https://itunes.apple.com/uk/app/my-beauty-squad/id1454212046?mt=8" ,
           url: base64Image,
           subject: "Share news feed"
         };
         Share.open(shareOptions);
         thisFun.changeLoaderStatus();
       })
     }).catch(error => {
       console.log(error, 'this is error');
       this.changeLoaderStatus();
     })
    }

Please let me know if anyone having a solution for the same.

**This is my app screen ** enter image description here

It's blur when we have long list items. enter image description here


Solution

  • Try this:

    import { captureRef } from react-native-view-shot

    constructor(props) { 
       super(props); 
       this.refs = {}; 
    }
    
    renderItem = ({item, index}) => (
       <TouchableOpacity 
           onPress={ () => { 
               captureRef(this.refs[`${index}`], options).then(.....)   
           }
       > 
          <View 
            style={{flexDirection:'row'}}
            ref={shot => this.refs[`${index}`] = shot}
          >
            ...........
          </View>
       </TouchableOpacity>
    )
    

    React Native View Shot

    I hope it help you.