Home > Back-end >  React JS - disable a button if the input field is empty?
React JS - disable a button if the input field is empty?

Time:11-28

React Code:

import { useState } from "react";

export default function IndexPage() {
  const [text, setText] = useState("");

  const autoComplete = (e) => {
    setText({ value: e.target.value });
  };

  return (
    <form>

      <input type="text" placeholder="search here" onChange={autoComplete} />

      <button type="submit" disabled={!text}> find </button>

    </form>
  );
}

SandBox Link: https://codesandbox.io/s/practical-panini-slpll


Problem:

when Page Loads, the find button is disabled at first because the input field is empty which is good. But,

Now, when I start typing something. then delete them all with Backspace key. the find button is not disabling again.


I want:

I just want to have my find button disabled if the input field is empty

Where I'm doing wrong?


CodePudding user response:

It's a common mistake coming from Class Components, state setter in hooks does not merge state value as in classes.

You initialized your state as a string (useState('')) and then assigned it as an object

const autoComplete = (e) => {
    setText({ value: e.target.value });
};

// State is an object { value: 'some text' }

Fix your set state call:

const autoComplete = (e) => {
    setText(e.target.value);
};

// State is a string 'some text'

Then to be more verbose you want to check if the string is empty:

<button disabled={text === ''}>find</button>

CodePudding user response:

disabled={!text.value}

Should do the trick. With this function

const autoComplete = (e) => {
  setText({ value: e.target.value });
};

you are writing your input in text.value, not in text.

CodePudding user response:

use this code for check text

<button type="submit" disabled={text==''}> find </button>
  • Related