Rajesh
Rajesh

Reputation: 556

refs are undefined in react native

Im new to react-native. Im trying to read x,y co-ordinates of a view inside its parent. Using below code

componentDidMount: function() {
  setTimeout(this.measureView);
},
measureView: function() {
  this.refs.completeView.measure((ox, oy, width, height) => {
    this.setState({headerHeight: height});
  });
},
render : function(){
return (
  <TouchableHighlight onPress={() => this.props._pressRow(this.props.currentRowID)}>
    <View style={styles.container}
          ref="completeView">
      <View style={styles.colorView}>
      </View>
      <View style={styles.textWrapper}>
        <Text style={styles.text}>{this.props.text}</Text>
      </View>
    </View>
  </TouchableHighlight>
);
},

Inside measureView, this.refs is always undefined. Why?

I'm trying to read last view's co-ordinates into ListView, because for some reason I want to render the last row. So is there any other solution for this?

Please also make a note that this class is being exported into its parent class.

Upvotes: 0

Views: 2836

Answers (2)

Tarek
Tarek

Reputation: 697

set ref using a function instead of a string:

var myComponent = null;

...

componentDidMount: function() {
  setTimeout(this.measureView);
},
measureView: function() {
  this.myComponent.completeView.measure((ox, oy, width, height) => {
    this.setState({headerHeight: height});
  });
},
render : function(){
return (
  <TouchableHighlight onPress={() => this.props._pressRow(this.props.currentRowID)}>
    <View style={styles.container}
          ref={((component)=>this.myComponent = component)}>
      <View style={styles.colorView}>
      </View>
      <View style={styles.textWrapper}>
        <Text style={styles.text}>{this.props.text}</Text>
      </View>
    </View>
  </TouchableHighlight>
);
},

Upvotes: 1

Aditya Singh
Aditya Singh

Reputation: 16650

Try using ES2015 lambda's to get the correct lexical value of this within methods.

measureView = () => {
  this.refs.completeView.measure((ox, oy, width, height) => {
    this.setState({headerHeight: height});
  });
},

Upvotes: 1

Related Questions