1

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?


3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

use this code for check text

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.