Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

refs not working in react-native

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?

like image 389
Tikli Taba Avatar asked Aug 11 '16 10:08

Tikli Taba


People also ask

Where refs Cannot be attached in React?

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.

Why ref is not recommended in React?

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.

Why refs are not recommended?

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.


2 Answers

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.

like image 98
Jeff P Chacko Avatar answered Nov 15 '22 10:11

Jeff P Chacko


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?

like image 34
Mila Avatar answered Nov 15 '22 11:11

Mila