1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.