How to achieve "e.target.value" in react native

Viewed 635

i wanna access button value in react native, in pure javascript it look like :

const checkingStuff = (e) => console.log(e.target.value)

<button onclick={checkingStuff} > this is the value </button>.

how to achieve the same thing in react native?

edit : please answer in react native, not react js, because

<Button
onPress={checkingStuff}
title='lalala123'/>

give me 'undefined'.

5 Answers

I don't know excatly what you try to achieve, however you should access the event directly in the input instead of the button. For TextInput in React Native, the changed text is passed as a single string argument to the callback handler.

You can try this

const [text, onChangeText] = useState("")
const onPress = () => {
   console.log(text)
}

return (
    <>
        <TextInput value={text} onChangeText={onChangeText}>
        <Button onPress={onPress}/>
    </>
)

event handlers give you inherent access to the event through the function. Unless specifically setting state within the DOM, there's no need to do an inline arrow function. You can simply reference the function like so:

const checkingStuff = (e) => { console.log(e.target.value) }

<button onClick={checkingStuff} > Set state and add your {value} like so </button>

If you import Button from react-native, this can be a solution for you

<Button title='here is your button text' onPress={(e)=>console.log(e._dispatchInstances.memoizedProps.children[0].props.children)}/>

But if you import Button from other source, or if this does not bring the exact value to this, then you can go upto e._dispatchInstances.memoizedProps.children then check your button text item position and get it in your own way.

I mostly used below methods :

  1. In the TextInput Itself.

     <TextInput
     style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
     onChangeText={text => console.log(text);
     value={value}
     />
    
  2. If using Class in react-native :

     <TextInput style = {styles.input}
            underlineColorAndroid = "transparent"
            placeholder = "Password"
            placeholderTextColor = "#9a73ef"
            autoCapitalize = "none"
            onChangeText = {this.handlePassword}/>
    

And this.handlePassword is :

 handlePassword = (text) => {
  this.setState({ password: text })

}

Of if you are using functional Component :

const [text, onChangeText] = React.useState("");
<TextInput
    style={styles.input}
    onChangeText={onChangeText}
    value={text}
  />

Happy Coding !!

You can get like this:

const checkingStuff = (e) => console.log(e.target.value)

<button onclick={(e) => checkingStuff(e)} > this is the value </button>
Related