evans
evans

Reputation: 563

how to change state?

I have a form, when I click on the button I have to show the message. The message has two states - setMessageShown (true); and setMessageShown (true);

How to change the state to true inside handleSubmit - setMessageShown(true);?

const handleSubmit = e => {
  e.preventDefault();
  // ...
};

const ReviewPopup = ({ name }) => {
  const [messageShown, setMessageShown] = useState(false);
  const hideMessage = () => {
    setMessageShown(false);
  };

  return (
    <form onSubmit={handleSubmit} className="new_review" id="new_review" action="/reviews" acceptCharset="UTF-8" method="post">
    // ...
    </form>
  );
};

Upvotes: 0

Views: 279

Answers (2)

Abin Thaha
Abin Thaha

Reputation: 4633

Try this way:

const ReviewPopup = ({ name }) => {
    const [messageShown, setMessageShown] = useState(false);

    const hideMessage = () => {
        setMessageShown(false);
    };

    const handleSubmit = () => {
        setMessageShown(true)
    }

    return (
        <form onSubmit={handleSubmit} className="new_review" id="new_review" action="/reviews" acceptCharset="UTF-8" method="post">
        // ...
        </form>
   );
};

This is how you can change state inside the react hooks.

Here, using useState, you are assigning a state variable and declaring a method with which you can change the state variable

const [messageShown, setMessageShown] = useState(false);

Here messageShown is the state variable and setMessageShown is the method with which you can change the state variable. That is what you are declaring in this line. The useState(false) means the initial value of the state variable messageShown.

Upvotes: 1

Philip Moy
Philip Moy

Reputation: 481

Put handleSubmit inside your component.

const ReviewPopup = ({ name }) => {
  const [messageShown, setMessageShown] = useState(false);
  const hideMessage = () => {
    setMessageShown(false);
  };

  function handleSubmit(e) {
    e.preventDefault();
    setMessageShown(true);
  }

  return (
    <form onSubmit={handleSubmit} className="new_review" id="new_review" action="/reviews" acceptCharset="UTF-8" method="post">
    // ...
    </form>
  );
};

Upvotes: 1

Related Questions