Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable or disable a button based on a TextField value in React.js

I am making a form like Screenshot form the form

I want the add button to be active whenever user is changing the "Tags" input text.

I am using material-ui and I made a Input component.

  const SingleInput = (props) => ( 
    <Fragment>
      <FormControl margin="normal" required fullWidth>
        <TextField
        id={props.id}
        type={props.type}
        name={props.name}
        label={props.label}
        value={props.content}
        variant={props.variant}
        placeholder ={props.placeholder}
        onChange={props.controlFunc}>
        </TextField>
      </FormControl>
    </Fragment>
  );
  export default SingleInput;

and I import this into my form and like:

class AddCompanyForm extends React.Component {
  constructor() {
    super();
    this.state = {
      company_name: "",
      company_description: "",
      company_tag: "",
      company_tags: "",
      company_contact: "",
      disabled: true
    };

    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.handleOnChange = this.handleOnChange.bind(this);
    this.handleOnSelect = this.handleOnSelect.bind(this);
  }
  handleOnChange(e) {
    e.preventDefault();
    this.setState({ [e.target.name]: e.target.value });
    this.setState({ disabled: false });
    console.log("teg", this.state.company_tag.length);
    console.log("cont", this.state.company_contact.length);
    if (this.state.company_tag.length == 1) {
      this.setState({ disabled: true });
    }
  }

  handleOnSubmit(e) {
    e.preventDefault();
    this.props.createCompany(this.state);
  }

  handleOnSelect(e) {
    e.preventDefault();
    chipsValue.push(this.state.company_tag);
    this.setState({
      company_tags: chipsValue,
      company_tag: "",
      disabled: true
    });
  }

  render() {
    return (
      <Paper style={styles.paper}>
        <Avatar>
          <LockIcon />
        </Avatar>
        <Typography variant="headline">Add a New Company</Typography>
        <form onSubmit={this.handleOnSubmit}>
          <SingleInput
            id={"company_name"}
            type={"company_name"}
            name={"company_name"}
            label={"Company Name"}
            content={this.state.company_name}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <SingleInput
            id={"company_description"}
            type={"company_description"}
            name={"company_description"}
            label={"Description"}
            content={this.state.company_description}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <SingleInput
            id={"company_tags"}
            type={"company_tags"}
            name={"company_tag"}
            label={"Tags (to add dropdown here!)"}
            content={this.state.company_tag}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <Button
            disabled={this.state.disabled}
            onClick={this.handleOnSelect}
            variant="raised"
            color="secondary"
          >
            Add
          </Button>
          <SingleInput
            id={"company_contact"}
            type={"company_contact"}
            name={"company_contact"}
            label={"Contact"}
            content={this.state.company_contact}
            controlFunc={this.handleOnChange}
            variant={"filled"}
          />
          <Button type="submit" fullWidth variant="raised" color="primary">
            Add Company
          </Button>
        </form>
      </Paper>
    );
  }
}
const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      createCompany
    },
    dispatch
  );
export default connect(
  null,
  mapDispatchToProps
)(AddCompanyForm);

Now the problem is even when I change "Company Name" or any other input button, the Add button becomes enabled.

Any help is very much appreciated.

like image 515
Manish Avatar asked Oct 18 '18 06:10

Manish


People also ask

How do you make button enable and disable in React JS?

Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!

How do you turn off input field based on condition React?

Disable the TextBox by adding the e-disabled to the input parent element and set disabled attribute to the input element.

How do you disable a button in React if input is empty?

To disable a button when an input is empty with React, we can set the input's value as a state's value. Then we can use the state to conditionally disable the button when the state's value is empty. to create the name state with the useState hook.


2 Answers

Check the example below using React Hooks for the button state, and the onChange property of the TextField to set it.

export default function TextFieldAndButton (props) {
  const [btnDisabled, setBtnDisabled] = useState(true)

  return (
    <>
        <TextField
          onChange={(text) => setBtnDisabled(!text.target.value)}
        />
        <Button disabled={btnDisabled}>OK</Button>
    </>
  )
}
like image 124
Jonathan Meller Avatar answered Oct 10 '22 08:10

Jonathan Meller


The problem here is that setState is async and you are using state values inside handleOnChange before it is updated. Either use setState callback to calculate disable or a better way is to calc disabled in render. This approach makes it much simpler and even works while rendering for the first time.

render() {
  const disabled = !this.state.company_tag.length;

  return (
    // ...
    <Button
      disabled={disabled}
      onClick={this.handleOnSelect}
      variant="raised"
      color="secondary"
    >
      Add
    </Button>
    // ...
  );
}
like image 23
Fawaz Avatar answered Oct 10 '22 08:10

Fawaz