Muhmmed Medhat
Muhmmed Medhat

Reputation: 3

Disable Button when input is empty in react

so I'm new at react and I have this problem when I want to disable Button when input is empty in react it only works one time until ;(

import React, { Component } from 'react';
class Form extends Component {
    render() {
        // start disable button when input is empty
        const success = () => {
            if (document.getElementById("id").value === "") {
                document.getElementById('button').disabled = true;
            } else {
                document.getElementById('button').disabled = false;
            }
        }
        // End disable button when input is empty
        return (
            <form onSubmit={this.props.addCourse}>
                <input onKeyUp={() => success()} id='id' value={this.props.value} type='text' onChange={this.props.updateCourse} />
                <button disabled id="button" type='submit'>Add Course</button>
            </form>


        );
    };

}


export default Form;

Upvotes: 0

Views: 1563

Answers (3)

newimprovement
newimprovement

Reputation: 72

It is generally unadvised to directly manipulate the DOM via react as react interacts with a virtual DOM to render a page.

see: https://dzone.com/articles/dom-manipulation-in-react

A better way to solve your problem is to check the value of by checking this.props.value instead of

if (document.getElementById("id").value === "")

You should also store whether the button is disabled or not in this.state

Given this, within your this.props.updateCourse you can have a check where

updateCourse(event) {
// If input value is equal to '' then
// Set button state to disabled
}

Upvotes: 0

Zunaib Imtiaz
Zunaib Imtiaz

Reputation: 3119

You could just do it like

  <form onSubmit={this.props.addCourse}>
                <input onKeyUp={() => success()} id='id' value={this.props.value} type='text' onChange={this.props.updateCourse} />
                <button disabled={this.props.value === ""} id="button" type='submit'>Add Course</button>
    //added condition to button disabled property
            </form>

If the value of this.props.value is empty it would return true and hence button will be disabled.

Upvotes: 1

Ace
Ace

Reputation: 1146

When using React, you don't want to access elements directly like you do with document.getElem.... You want to create a state. What you want to do is create a variable disabled that is true when the input is empty, false otherwise. Then when it comes to adding the disabled property to the button: <button disabled={disabled}...>. So now the disabled property of the button will be the value of your disabled variable.

Upvotes: 0

Related Questions