Edgar
Edgar

Reputation: 927

React Native. Can't set ref from within a map function

I am trying to create a ref for each component that I create with a map function.

This is my component:

class Foo extends Component {

constructor(props) {
   super(props)
}

render() {
  return (
   <ScrollView>
     {this.state.barList.map(createSlides)}
   </ScrollView>
)
}

const createSlides = (uri, i) => (<CarouselItem
                        onPress={() => {}}
                        imgUrl={uri}
                        itemWidth={carouselItemWidth}
                        padding={carouselItemPadding}
                        key={i}
                        ref={(slide) => { this['slide_' + i] = slide}}
                      />);

as you see I am setting a ref, but later when trying to access refs it gives me undefined. Where is my mistake?

Upvotes: 3

Views: 3828

Answers (1)

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

Try putting the createSlides method in your Component

class Foo extends Component {

  constructor(props) {
    super(props)
    // make sure this method gets the right scope, no matter how it's called
    this.createSlides = this.createSlides.bind(this)
  }

  render() {
    return (
      <ScrollView>
        {this.state.barList.map(this.createSlides)}
      </ScrollView>
    )
  }

  createSlides(uri, i) {
    return (<CarouselItem
      onPress={() => { }}
      imgUrl={uri}
      itemWidth={carouselItemWidth}
      padding={carouselItemPadding}
      key={i}
      ref={(slide) => { this['slide_' + i] = slide }}
    />)
  }
}

Upvotes: 3

Related Questions