How to disable a TextInput in React Native

You might have some TextInput's in your application that you want to disable at certain points.

If you are coming from the web, you might have expected a disabled prop. But, in React Native, we use the editable property.

It's pretty easy just add editable={false}.

As a bonus, if you want to stop copying/selecting text from the disabled field, you can also add selectTextOnFocus={false}.

Here's an example of the editable and selectTextOnFocus prop in action:

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


const App = () => {
  // disabled by default:
  const [isEditable, setIsEditable] = useState(false);

  const toggleEdit = () => {
    setIsEditable(!isEditable);
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        editable={isEditable}
        selectTextOnFocus={isEditable}
        value="This text can be edited if you press the button."
      />
      <Button
        title={isEditable ? "Make Uneditable" : "Make Editable"}
        onPress={toggleEdit}
      />
    </View>
  );
};

// Because we want to make it pretty 💄
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#999',
    width: '100%',
    marginBottom: 20,
    padding: 10,
  },
});

In this example, there's a button that when you press you can toggle the editable prop to true or false. You can then test out the result for yourself, and see that the field is enabled or disabled depending on the editable state.

Now you can try it out in your own app!

React Native
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.