Arpith Siromoney đź’¬

Disabling Buttons in React Native

I’m building an app to share notes called Constellational (sign up here!) andI’ve wanted to prevent blank posts and “updates” that don’t really have changes. To do this, I’ve disabled the Post and Update buttons unless there is a change from the initial state (this will be a blank string if we’re creating a new post).



This is how I did it in React Native. In the constructor for my EditPage component:

this.state.shouldDisablePostButton = true;
if (this.state.post.isDraft) {
 this.state.shouldDisablePostButton = false;
}

Note that if it’s a draft we’re editing, we’re never going to want to disable the Post button.

In the EditPage component’s render method:

var postButton = <PostButton 
 edit={this.isEditing}
 isDraft={this.state.post.isDraft}
 onPress={this.savePost}
 disabled={this.state.shouldDisablePostButton}
/>;

The onChangeText method for the TextInput also needed to be changed:

onChangeText={(text) => {
 this.state.post.data = text;
 this.setState({
   shouldDisablePostButton: !this.state.post.isDraft && (this.state.post.data === this.initialData)
 });
}}

The PostButton component uses the React Native Buttons package:

var Button = require('react-native-button');
class PostButton extends React.Component {
 render() {
   var text = 'Post';
   if (!this.props.isDraft && this.props.edit) text = 'Update';
   return <Button
     onPress={this.props.onPress}
     style={styles.postButton}
     styleDisabled={styles.disabled}
     disabled={this.props.disabled}
   >
     {text}
   </Button>;
 }
}

And that’s it! This fixes #66.