Ijaz Ali
Ijaz Ali

Reputation: 73

How to get the text of textinput in react native?

How to write this statment, like in ios, in React syntax:

txt1.text = label.text 

I tried a lot but failed.

import React, { Component } from 'react';
import { View, Text, Button, TextInput } from 'react-native';

export default class App extends Component {
state = {
TextInputValue: '',
  };

onPress = () => {
this.setState({
  //textValue.Text: TextInputValue,
  //newText: textValue
});
  };

render() {
return (
  <View style={{ paddingTop: 25 }}>

    <TextInput
      style={{ height: 40 }}
      placeholder="Type here to! Translate"
      onChangeText={TextInputValue => this.setState({ TextInputValue })}
    />
    <Button title="Change Text" onPress={this.onPress} 
    />

    <Text>
      {this.state.newText}
    </Text>
  </View>
);
}
 }

When the button is pressed, I want to get the text of textinput and display it on Text (Label)

Upvotes: 4

Views: 2888

Answers (2)

Abraham
Abraham

Reputation: 9885

Instead of having to update your state with a button, you can update it while typing in, check the demo below (I am using hooks, but it is the same thing with regular state):

import React, { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export default () => {
  const [input, setInput] = useState('Default Text');

  return (
    <View style={styles.container}>
      <Text>{input}</Text>
      <TextInput
        style={styles.input}
        placeholder="Type here!"
        onChangeText={input => setInput(input)}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingTop: 50,
    alignItems: 'center',
  },
  input: {
    marginTop: '60%',
    height: 40,
    width: '80%',
  },
});

Upvotes: 0

Joseph D.
Joseph D.

Reputation: 12174

Two missing elements:

  1. Define newText in the state structure.
state = {
  TextInputValue: '', // for onChangeText handler
  newText: '', // for button onClick handler
};
  1. Implement button onClick handler to set newText state.
onPress = () => {
  this.setState({
    newText: this.state.TextInputValue,
  });
}

See Code Sandbox demo

Upvotes: 1

Related Questions