Skip to content

Render a new value into TextInput React Native

I’ve got a react native form with a button that should autofill some of the field based on some user’s information. The point is that even if I update the state variable related to a TextInput, the TextInput does not display such data. Here’s a short snippet for the sake of simplicity

export default class Component extends React.Component {    
    constructor(props) {
        super(props);

        this.state = {
            value: null
        }
    }

        autocompile = () => {
            this.setState({"value": "new value"})
        }
        
        render() {
            return (
                <View>
                  <TouchableOpacity
                    onPress={() => {
                      this.autocompile
                    }}>
                    <Text>Autocompile</Text>
                  </TouchableOpacity>
                  <TextInput
                      onChangeText={(value) => this.setState({'value': value})}
                      value={this.state.value}
                  />
                </View>
            )
        }
    }
}

Following this example, if I clicked “Autocompile”, the TextInput below wouldn’t show the new value, even though the state variable would be updated. My question is, how can I update a TextInput displayed value from the external without typing in?

Answer

Class Component Solution

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

export default class Component extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
    this.autocompile = this.autocompile.bind(this);
  }

  autocompile() {
    this.setState({ value: 'new value' });
  }

  render() {
    return (
      <View>
        <TouchableOpacity onPress={this.autocompile}>
          <Text>Autocompile</Text>
        </TouchableOpacity>
        <TextInput
          onChangeText={(value) => this.setState({ value: value })}
          value={this.state.value}
        />
      </View>
    );
  }
}

Function Component Solution

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

const App = () => {
  const [value, setValue] = useState('');

  const autocompile = () => setValue('new value');

  return (
    <View>
      <TouchableOpacity onPress={() => autocompile()}>
        <Text>Autocompile</Text>
      </TouchableOpacity>
      <TextInput onChangeText={(value) => setValue(value)} value={value} />
    </View>
  );
};

export default App;