So I've coded this react small react form specifically for this question and I want to add a feature to it.
Here's the code:
import React, { useState } from "react";
export default function App() {
const [formInfo, setFormInfo] = useState({ name: "", email: "" });
function onch(e) {
const { value, id } = e.target;
id === "name"
? setFormInfo({ ...formInfo, name: value })
: setFormInfo({ ...setFormInfo, email: value });
}
function onsub(e) {
e.preventDefault();
const { name, email } = formInfo;
if (name === "") {
alert("fill your name");
} else if (email === "") {
alert("fill out your email");
} else {
alert("done");
setFormInfo({ name: "", email: "" });
}
}
const { name, email } = formInfo;
return (
<form action="" onSubmit={onsub}>
<div className="input">
<label htmlFor="">Name</label>
<input type="text" name="" id="name" onChange={onch} value={name} />
</div>
<div className="input">
<label htmlFor="">E-mail</label>
<input type="text" name="" id="email" onChange={onch} value={email} />
</div>
<div className="input">
<button type="submit">Submit</button>
</div>
</form>
);
}
You see if you didn't fill out one of the inputs it will trigger an alert. But I want to replace the alert with focus instead. So when I forgot to fill out a certain input it will focus on that empty input basically telling me to fill it out.
THANK YOU IN ADVANCE
You can create something like this which use createRef() api of react.
This sample is taken from react.org