简体   繁体   中英

Why I cant share info between form input (child component) and React useState Hook (parent component)?

I am doing a multiple step form with React and I expect that when the user hits "Next" button, he/she can go to the next form, save info in parent component useState Hook and keep it in the input if user decides to go back. Switch has 8 cases but I left only 1 for simplicity. Structure looks something like this (Questions after code):

<MainForm /> |_ <UserInfo /> |_ Another 7 childs

MainForm.js

import React, { useState } from "react";

import UserInfo from "../components/Shared/UserInfo";
//import ... more childs ...
import {
  BackButton,
  NextButton,
  SendButton,
} from "../components/Shared/Buttons";

const BDMForm = (props) => {
  const [step, setStep] = useState(1);
  const [datos, setDatos] = useState({
    fullName: "",
    email: "",
    phoneNumber: "",
    linkedIn: "",
    city: "",
    experience: "",
  });

  const handleChange = (e) => {
    setDatos({ ...datos, [e.target.name]: e.target.value });
  };
  function renderComponent(step) {
    let currentStep = step;

    switch (currentStep) {
      case 1:
        return <UserInfo handleChange={handleChange} datos={datos.fullName} />;

      // 7 more cases
}
  return (
    <form>
      {renderComponent(step)}
      <div className="button-container">
        <BackButton step={step} setStep={setStep} />
        {step >= 7 ? null : <NextButton step={step} setStep={setStep} />}
        {step === 7 ? <SendButton /> : null}
      </div>
    </form>
  );
};

export default MainForm;

UserInfo.js

import React from "react";

  return (
        <div className="card-container">
          <label>
            Nombre y Apellido<span> *</span>
          </label>
          <input
            type="text"
            name="fullName"
            value={props.datos}
            onChange={props.handleChange}
          />
        </div>
      </div>
  );
};

export default UserInfo;

I have 2 questions:

1) When I write something on fullName input (UserInfo.js), I think React is updating the component with the default value ("") so I cant write anything on it. Expected behavior: User can write and input should be saved in datos.fullName on parent component. When user press Next or back, written information will still be there.

2) Is my approach OK? Should I be saving all children data in parent component and then access it from another child later on (Like Confirm.js or somewhere where the user can read the information before send it). I tried to learn Context API but still don't understand how to implement it

Change your handleChange function like this:

  const handleChange = (e) => {
    const fieldName = e.target.name;
    const fieldValue = e.target.value;
    setDatos(prevDatos => ({ ...prevDatos, [fieldName]: fieldValue }));
  };

When the new state depends on the previous state you have to use the functional way to update the state.

Regarding your second question, yes, your approach is fine.

And finally, I would maintain some consistency when defining the functions. I'm referring to handleChange and renderComponent functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM