skip to Main Content

I’m starting developing form in React and I’ve made every field of form a separate component. So, from picture below:
Component A – is form with submit function
Component B – is file input (for example)

How to fetch state objects of nested components after clicking Submit button? I know that I can pass function to nested components witch will update parent state but maybe there is better solution?

enter image description here

2

Answers


  1. `Component A 
      import React, { useState } from 'react';
      export default function componentA(){
      const [componentA, setcomponentA] = useState("A Component")
       return(
             <>
              <div>
                <ComponentB Data = {componentA} />
              </div>
             </>
           )
      }
    Component B 
    import React, { useState } from 'react';
    export default function componentB({Data}){
    return(
          <>
            <div>
              <h1>{Data}</h1>
            </div>
         </>
       )
     }`
    
    Login or Signup to reply.
  2. In React, you have several options for managing and collecting state from nested components when a form is submitted. Here are some common approaches

    // Component A (parent)
    function FormComponent() {
      const [formData, setFormData] = useState({/* initial form data */});
      
      const handleFormSubmit = () => {
        // Access formData and submit the form
      }
    
      return (
        <div>
          <ComponentB formData={formData} setFormData={setFormData} />
          {/* Other form fields */}
          <button onClick={handleFormSubmit}>Submit</button>
        </div>
      );
    }
    
    // Component B (child)
    function ComponentB({ formData, setFormData }) {
      const handleFileChange = (event) => {
        // Update formData with the file data
        setFormData({ ...formData, file: event.target.files[0] });
      }
    
      return (
        <input type="file" onChange={handleFileChange} />
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search