CI_Guy
CI_Guy

Reputation: 1039

Disabling a button within a stateless component - react

I'm trying to figure out how I can set a disabled field in a stateless component that only uses prop. The stateless component has a input field that if empty I would like to disable the submit button within the same component. I was able to update the parent's state via a prop to the child and so wanted to keep it with no state but starting to think I may need it for checking if the button can be enabled or not.

I've tried different methods using refs etc. Here is a codesandbox project I have for an example

https://codesandbox.io/s/840kkk03l

The stateless prop is :

const Childprop = function(props) {
  function handleNameChange(e) {
    e.preventDefault();
    props.onNameChange(e.target.newName.value);
  }
  function checkDisabled() {
    var input = document.getElementById("input");
    if (input.value === "") {
      return true;
    } else {
      return false;
    }
  }
  return (
    <p>
      The logged in user is: {props.nameProp}
      <form onSubmit={handleNameChange}>
        <input name="newName" type="text" id="input" />
        <input type="submit" disabled={checkDisabled} />
      </form>
    </p>
  );
};

Thank you

Upvotes: 0

Views: 2362

Answers (3)

ChezFre
ChezFre

Reputation: 6512

I'd use a local state just for the value of the input. This would make it a controlled component.

class Childprop extends React.Component {
    state = {
        newName: ''
    }

    handleNameChange = (e) => {
        e.preventDefault();
        props.onNameChange(this.state.newName);
        this.setState({ newName: '' });
    }

    render() {
        return (
            <div>
                The logged in user is: {props.nameProp}
                <form onSubmit={handleNameChange}>
                    <input name="newName" type="text" id="input" onChange={(e) => this.setState(e.target.value)} value={this.state.newName} />
                    <input type="submit" disabled={this.state.newName.length === 0} />
                </form>
            </div>
        );
    }
};

Upvotes: 1

Anas
Anas

Reputation: 5727

You can make it work like this: https://codesandbox.io/s/rr6jw0xxko

The only issue is once the button is disabled, there is no way to enable it again since you cannot submit anymore.

I agree that @azium way is the React way.

Upvotes: 0

azium
azium

Reputation: 20614

This cannot be done. Something in your app must call setState, forceUpdate or the root application be re-rendered for your stateless function to be called again.

Upvotes: 0

Related Questions