TheDareback
TheDareback

Reputation: 407

How to display warning message of invalid input div in React?

I'm working on a new form in React, where I need to validate inputs and, in case of incorrect input, display alerts individually under each bad input.

What is the better solution?

  1. Create a div in advance under each input and hide and show it with the help of classes.
<label htmlFor="first-name"></label>
<input type="text" name="first-name" id="first-name" />
<div className="invalid-input disable/enable">Please fill in your name.</div>
  1. Create an auxiliary function that performs validation and then adds this warning div under each input.
const div = document.createElement("div")
div.innerHTML = "Please fill in your name.";

const input = document.getElementById("first-name");
insertAfter(div, input);

What is conventionally correct?

Upvotes: 1

Views: 2089

Answers (1)

Kirill
Kirill

Reputation: 11

You can create an error state as a boolean variable or object with errors for each field using useState.

const [error, setError] = useState(false)

Further display an error through such a record:

{error && <div>message error</div>}

If errors = false, then the message does not appear

Upvotes: 1

Related Questions