Ismail Ch
Ismail Ch

Reputation: 33

How to get Text component value onPress in react-native

I'm a new react-native developer. I want to get the value of Text component using onPress and pass it to a function.

<Text onPress={()=>this.display}>Hello World</Text>


display= (text) =>{
    console.log(text);//this should print Hello world
  }

Upvotes: 3

Views: 7214

Answers (5)

Missoum Said
Missoum Said

Reputation: 36

onPress={(e) => console.log(e, word)}

Class {dispatchConfig: {…}...} 'word'

word argument will carry the value of the component inner text, and the e will carry the event object.

practical example:

const wordSelected = (e, word) => {
    console.log(word);
  };

  <TouchableOpacity onPress={(e) => wordSelected(e, word)}>
              <Text>print me out</Text>
            </TouchableOpacity>

print me out

Upvotes: 1

Vishal Mathimaran
Vishal Mathimaran

Reputation: 351

This method can be used to get text from a text onPress event

 <Text onPress={(event) => console.log(event._dispatchInstances.memoizedProps.children)} >{value}</Text>

Upvotes: 9

Rishav Kumar
Rishav Kumar

Reputation: 5450

<Text onPress={()=>this.display('Hello World')}></Text>


display= (text) =>{
    console.log(text);//this should print Hello world
  }

Try this

Upvotes: -3

Andrew Zheng
Andrew Zheng

Reputation: 2858

I'm not an expert on React Native. I got some ideas from this Stackoverflow Link

But I think you can set up a ref on the Text component

<Text ref={(elem) => this.textElem = elem} onPress={()=>this.display}>Hello World</Text>

For your event handler, you can do

display = () =>{
    console.log(this.textElem.props.children);//this should print Hello world
}

Upvotes: 2

Antoine Vo
Antoine Vo

Reputation: 571

You need can use the ref attribute to access the button's Text value.

<Text ref='myText'>This is my text</Text>
<Button onPress={()=>this.display(this.refs.myText.props.children)} title='Press Me'/>

//this should print Hello world
display= (text) =>{
    console.log(text);
}

Alternatively, just store it in a variable:

const myText = "This is my text"

<Text onPress={()=>this.display}>{myText}</Text>

display = () => {
     console.log(myText);
}

Upvotes: 0

Related Questions