Advertisement
Larrisa

react form

Sep 30th, 2024
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. import React, { useState } from 'react';
  2.  
  3. const MyForm = () => {
  4. const [formData, setFormData] = useState({
  5. name: '',
  6. email: '',
  7. });
  8.  
  9. const handleChange = (e) => {
  10. const { name, value } = e.target;
  11. setFormData({
  12. ...formData,
  13. [name]: value,
  14. });
  15. };
  16.  
  17. const handleSubmit = async (e) => {
  18. e.preventDefault(); // Prevent the default form submission
  19.  
  20. try {
  21. const response = await fetch('https://example.com/api/data', {
  22. method: 'POST',
  23. headers: {
  24. 'Content-Type': 'application/json',
  25. },
  26. body: JSON.stringify(formData),
  27. });
  28.  
  29. if (!response.ok) {
  30. throw new Error('Network response was not ok');
  31. }
  32.  
  33. const result = await response.json();
  34. console.log('Success:', result);
  35. } catch (error) {
  36. console.error('Error:', error);
  37. }
  38. };
  39.  
  40. return (
  41. <form onSubmit={handleSubmit}>
  42. <div>
  43. <label>
  44. Name:
  45. <input
  46. type="text"
  47. name="name"
  48. value={formData.name}
  49. onChange={handleChange}
  50. required
  51. />
  52. </label>
  53. </div>
  54. <div>
  55. <label>
  56. Email:
  57. <input
  58. type="email"
  59. name="email"
  60. value={formData.email}
  61. onChange={handleChange}
  62. required
  63. />
  64. </label>
  65. </div>
  66. <button type="submit">Submit</button>
  67. </form>
  68. );
  69. };
  70.  
  71. export default MyForm;
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement