javascriptreactjsreact-nativevalidationreact-native-elements

How to apply an action on disabled button press in react native elements Button component?


Let's say there is a form with an input. The submit button is disabled until there is an input in the input element.

When the user enters the input, the submit button is enabled and the user can easily submit the form. But in case when there is no input and the user press the disabled submit button, the onDisabledPress() handler should be taken into action.


Solution

  • It's just about your logic there is no need for external function. You will need a state to tell the button the way it should render, I called it is submitable. When submitable is true, the button will have active style, and when false it should use disabled style. For example:

    const submitable = state.formInput1.length > 0 && state.formInput2.length > 0;
    
    return (
       <TouchableOpacity
          style={submitable ? styles.active : styles.disabled}
          onPress={()=> {
             if (submitable) {
                console.log("Success")
             } else {
                console.log("You must input all required field")
             }
          }}
       ><Text>Submit</Text></TouchableOpacity>
    )
    
    const styles = {
       active: {
          backgroundColor: 'blue',
       },
       disabled: {
          backgroundColor: 'gray',
          opacity: 0.5,
       }
    }