Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
How can I use this React component to collect form data?

I've created two components which together create a 'progressive' style input form. The reason I've chosen this method is because the questions could change text or change order and so are being pulled into the component from an array stored in a JS file called CustomerFeedback.

So far I've been trying to add a data handler function which will be triggered when the user clicks on the 'Proceed' button. The function should collect all of the answers from all of the rendered questions and store them in an array called RawInputData. I've managed to get this to work in a hard coded version of SurveyForm using the code shown below but I've not found a way to make it dynamic enough to use alongside a SurveyQuestion component. Can anybody help me make the dataHander function collect data dynamically?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There what I have done:

https://codesandbox.io/s/angry-dew-37szi2?file=/src/InputForm.js:262-271

So, we can make it easier, you just can pass necessary data when call handler from props:

  const inputRef = React.useRef();

  const handleNext = () => {
    props.clickHandler(props.reference, inputRef.current.value);
  };

And merge it at InputForm component:

  const [inputData, setInputData] = useState({});

  const handler = (thisIndex) => (key, value) => {
    if (thisIndex === currentIndex) {
      setCurrentIndex(currentIndex + 1);
      setInputData((prev) => ({
        ...prev,
        [key]: value
      }));
    }
  };

  // ...
    <Question
        // ...
        clickHandler={handler(question.index)}
      />

So, you wanted array (object more coninient I think), you can just save data like array if you want:

setInputData(prev => [...prev, value])

Initially, I thought you want to collect data on button clicks in the InputForm, but apparently you can do without this, this solution is simpler

UPD Apouach which use useImperativeHandle: If we want to trigger some logic from our child components we should create handle for this with help of forwarfRef+useImperativeHandle:

const Question = React.forwardRef((props, ref) => {
  const inputRef = React.useRef();

  React.useImperativeHandle(
    ref,
    {
      getData: () => ({
        key: props.reference,
        value: inputRef.current.value
      })
    },
    []
  );

After this we can save all of our ref in parent component:

  const questionRefs = React.useRef(
    Array.from({ length: QuestionsText.length })
  );

  // ...

  <Question
     key={question.id}
     ref={(ref) => (questionRefs.current[i] = ref)}

And we can process this data when we want:

  const handleComplete = () => {
    setInputData(
      questionRefs.current.reduce((acc, ref) => {
        const { key, value } = ref.getData();
        return {
          ...acc,
          [key]: value
        };
      }, {})
    );
  };

See how ref uses here: https://reactjs.org/docs/forwarding-refs.html https://reactjs.org/docs/hooks-reference.html#useimperativehandle

I still strongly recommend use react-hook-form with nested forms for handle it

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda