Instead of re-rendering the entire component-tree whenever "<InputText style{...}>" is changed, I am trying to use refs in my Class Component. (I am using React Native with Expo managed workflow.)
Using refs, the typed text appears as it should in the InputText field. But, when a button is pressed, the value of the typed text (value of the InputText) should be console logged, however it is not.
export class Feed extends Component {
constructor(props){
super(props);
this.state = {
//some state variables
}
this.myTextFromInput = React.createRef()
}
I started by creating the myTextFromInput ref (above).
<TextInput
style={{height:100}}
ref={this.alias}
placeholder="Input Text Here"
/>
I then used the myTextFromInput ref in the InputText component. And lastly, the button!
<Button onPress={()=>console.log(this.myTextFromInput.current.value)}>Press me!</Button>
This gives me undefined
. I have also tried this.myTextFromInput.value
and a .getText() method which is outdated.
How can I obtain the inputed text?
UPDATE:
Terminal log undefined
. But snack works fine!?
You aren't passing the correct reference to TextInput
, it should be this.myTextFromInput
not this.alias
, take a look:
export class Feed extends Component {
constructor(props){
super(props);
this.state = {
//some state variables
}
this.myTextFromInput = React.createRef()
// bind the method to the component instance
this.logInputText = this.logInputText.bind(this)
}
logInputText() {
console.log(this.myTextFromInput.current.value)
}
render() {
return (
<View>
<TextInput
style={{height:100}}
// pass the correct reference here
ref={this.myTextFromInput}
placeholder="Input Text Here"
/>
<Button
onPress={this.logInputText}>
Press me!
</Button>
</View>
)
}
}
Also don't forget that whether you use a method instead of arrow function you've to bind it to the class instance, like I did. See this question and this example from react docs.
Update: React.ref
on Android and iOS doesn't seems to work as the same way as it works on web, you can't get the value from input because the component doesn't provide this property, doing a console.log(this.myTextFromInput.current)
you can see all the available properties. One solution from this question is to use TextInput from the package react-native-paper, as it provides the input value from the ref, or you could use the common state approach to store the input value, like so:
export class Feed extends Component {
constructor(props){
super(props);
this.state = {
myTextFromInput: ""
}
// bind the method to the component instance
this.logInputText = this.logInputText.bind(this)
}
logInputText() {
console.log(this.state.myTextFromInput)
}
render() {
return (
<View>
<TextInput
style={{height:100}}
// you don't need to use ref
placeholder="Input Text Here"
onChangeText={(text) => this.setState({myTextFromInput: text})}
/>
<Button
onPress={this.logInputText}>
Press me!
</Button>
</View>
)
}
}