different form examples

This commit is contained in:
e560248
2025-04-07 15:07:00 +02:00
parent 8a3165a26d
commit 048120adae
2 changed files with 74 additions and 0 deletions

View File

@@ -40,3 +40,8 @@
.read-the-docs { .read-the-docs {
color: #888; color: #888;
} }
input[type="text"] {
border-radius: 6px;
padding: 1rem 0.5rem;
}

View File

@@ -0,0 +1,69 @@
import { FormEvent, useRef, useState } from "react";
export default function RefExercise(): React.ReactElement {
console.log("RefExercise rendered");
const emailRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
const handleSubmit = () => {
console.log("submit", {
email: emailRef.current?.value,
password: passwordRef.current?.value
});
passwordRef.current?.focus();
}
const [formData, setFormData] = useState({
strasse: "",
city: ""
});
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setFormData({
...formData,
[event.target.name]: event.target.value
});
}
const handleChangeSubmit = () => {
const strasse = document.querySelector('input[name="strasse"]') as HTMLInputElement;
const city = document.querySelector('input[name="city"]') as HTMLInputElement;
console.log("submit", {
strasse: strasse.value,
city: city.value
});
}
function handleFormSubmit(e: FormEvent) {
e.preventDefault();
const data = new FormData(e.target as HTMLFormElement);
console.log('handleFormSubmit', {
email: data.get('email'),
password: data.get('password')
});
}
return (
<div style={{ display: "flex", flexDirection: "column", gap: "3rem" }}>
<div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
<h3>values by ref</h3>
<input type="text" placeholder="email" ref={emailRef}/>
<input type="text" placeholder="password" ref={passwordRef}/>
<button onClick={handleSubmit}>Submit</button>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
<h3>change event (bad way, but validation is possible)</h3>
<input type="text" name="strasse" placeholder="Strasse" onChange={handleChange} />
<input type="text" name="city" placeholder="Stadt" onChange={handleChange}/>
<button onClick={handleChangeSubmit}>submit</button>
</div>
<form onSubmit={handleFormSubmit} style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
<h3>By Form Event</h3>
<input type="text" name="email" placeholder="Email" />
<input type="text" name="password" placeholder="password" />
<button type="submit">Send</button>
</form>
</div>
);
}