Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda