Form Handling In React With Axios
import { useState, useRef } from "react";
import axios from "axios"; // Import Axios
import "./App.css";
function App() {
const [details, setDetails] = useState({
username: "",
password: "",
});
const ref = useRef();
const handleChange = (e) => {
const { name, value } = e.target;
setDetails((prev) => {
return { ...prev, [name]: value };
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(
"https://example.com/api/endpoint",
details
);
console.log(response.data); // Log the response from the API
ref.current.reset();
} catch (error) {
console.error("Error submitting form:", error);
}
};
return (
<>
<h2>OnChange Method In React</h2>
<form ref={ref} onSubmit={handleSubmit}>
<div>
<label style={{ padding: "5px" }} htmlFor="username">
Username
</label>
<input
type="text"
placeholder="Enter username..."
name="username"
onChange={handleChange}
/>
</div>
<div>
<label style={{ padding: "5px" }} htmlFor="password">
Password
</label>
<input
type="password"
placeholder="Enter password..."
name="password"
onChange={handleChange}
/>
</div>
<br />
<button type="submit">Submit</button>
</form>
</>
);
}
export default App;
