Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from 'react';
- const MyForm = () => {
- const [formData, setFormData] = useState({
- name: '',
- email: '',
- });
- const handleChange = (e) => {
- const { name, value } = e.target;
- setFormData({
- ...formData,
- [name]: value,
- });
- };
- const handleSubmit = async (e) => {
- e.preventDefault(); // Prevent the default form submission
- try {
- const response = await fetch('https://example.com/api/data', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(formData),
- });
- if (!response.ok) {
- throw new Error('Network response was not ok');
- }
- const result = await response.json();
- console.log('Success:', result);
- } catch (error) {
- console.error('Error:', error);
- }
- };
- return (
- <form onSubmit={handleSubmit}>
- <div>
- <label>
- Name:
- <input
- type="text"
- name="name"
- value={formData.name}
- onChange={handleChange}
- required
- />
- </label>
- </div>
- <div>
- <label>
- Email:
- <input
- type="email"
- name="email"
- value={formData.email}
- onChange={handleChange}
- required
- />
- </label>
- </div>
- <button type="submit">Submit</button>
- </form>
- );
- };
- export default MyForm;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement