I have a TextInput which I want to reference in my function.
next() {
let body = this.refs.body.value
}
<View>
<Text>Place the body here</Text>
<TextInput ref="body" placeholder="Your body goes here..." style={styles.body} placeholderTextColor='green'/>
</View>
But I am getting this error:
undefined is not an object (evaluating 'this.refs.body')
Is ref
not working in react-native?
When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current . You may not use the ref attribute on function components because they don't have instances.
We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.
Refs suggest that you can communicate with other components using the ref attribute. This would get the information to the desired destination, however, you'll lose data-driven actions in your application since refs won't ensure data synchronization. State will not update and components will not re-render.
I think they have changed the way ref works. Now instead of a string, ref accepts a function that gets called when the particular component gets rendered.
You could try something like,
next() {
let body = this._textInput.value
}
<View>
<Text>Place the body here</Text>
<TextInput ref={component => this._textInput = component} placeholder="Your body goes here..." style={styles.body} placeholderTextColor='green'/>
</View>
https://facebook.github.io/react-native/docs/direct-manipulation.html
Or, you could also attach an onChange to your TextInput and record the input when the next button is clicked.
EDIT:
Ref still accepts string but it is to be deprecated. Use the function in ref instead.
The problem may be related to the fact that you refer to an element which is not mounted yet. Did you make sure to refer to it on componentDidMount
or later?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With