7

I want to disable/enable a form submit button using a function.
Here is my code to explain what I want:

isDisabled = () => {
    //logic to define if button should be disabled or not
    //return boolean true or false based on that
}


render() {
    return (
        <form className="forgot-password-form">
            //form fields
            <input type="submit" value="Submit" disabled={this.isDisabled} />
        </form>
    );
}

This is just to show an idea what I want to do :) Of course render() will be in component and all.

Currently it gives me warning:

Warning: Invalid value for prop disabled on tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

Thank you all for your help.

Ivan Vasiljevic
  • 5,478
  • 2
  • 30
  • 35
Abhay Maurya
  • 11,819
  • 8
  • 46
  • 64
  • are you using onSubmit? if so you can just have a helper that returns the code you want to execute if not disabled and if disabled it just runs a function that returns false – Eric Hasselbring Feb 20 '18 at 14:58
  • https://codesandbox.io/s/n95yyov50 – RIYAJ KHAN Feb 20 '18 at 14:58
  • onSubmit will run when you click on submit, I don't want to let a user click on submit button if form is not having certain conditions fulfilled. Kind of same like invalid functionality in angular which comes out of the box. – Abhay Maurya Feb 20 '18 at 14:59
  • @ RIYAJ KHAN I dont understand how that answers my question :) You are disabling it always and making a function call onClick :D – Abhay Maurya Feb 20 '18 at 15:01
  • If you can disable when the inputs of the form are empty, you can check by the state, something like [this](https://stackoverflow.com/questions/30187781/react-js-disable-button-when-input-is-empty) – BrTkCa Feb 20 '18 at 15:11

2 Answers2

21

You're passing a function to the disabled prop, you have to execute this function to pass the boolean result of this function instead :

<input type="submit" value="Submit" disabled={this.isDisabled()}
Dyo
  • 4,429
  • 1
  • 15
  • 30
0

    <meta charset="UTF-8">
    <script src="https://unpkg.com/react@0.13.3/dist/react.js"></script>
    <script src="https://unpkg.com/react@0.13.3/dist/JSXTransformer.js"></script>
    <div id="app"></div>
    <script type="text/jsx;harmony=true">void function() { "use strict";

var App = React.createClass({
  getInitialState() {
    return {}
  },
  isDisabled(){
    return true;   // for disable button return true otherwise false
   // return false;
  },
  render() {
    return <div>
<input type="submit" value="Submit" disabled={this.isDisabled()}/>
    
    </div>
  }
})

React.render(<App/>, document.getElementById('app'))

}()</script>
Pulkit Aggarwal
  • 2,554
  • 4
  • 23
  • 33