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

112
Visualizações
Helper function reactjs

I created a helper function to reduce some functions in components. So whenever I need that helper function I could use them in the component needed. I don't know what is the correct way of doing it but I tried this way. I need to pass form, setForm state and event to the helper function. For example.
Main.js

import { useState } from "react";
// helper
import HandleChange from "./HandleChange";

function Main() {
    const [form, setForm] = useState({
        firstName: "",
        lastName: "",
    });

    // ------> This is what I want to move to helper component.
    // function handleChange(event) {
    //   const { name, value } = event.target;

    //   setForm({
    //     ...form,
    //     [name]: value,
    //   });
    // }

    // ------> This is how I used helper component
    const handleChange = HandleChange(form, setForm, event);
    return (
        <input
            type="text"
            name="firstName"
            value={form.firstName}
            {/****** this is how I passed handleChange ******/}
            onChange={handleChange}
        />
    )
}

Helper.js

export default function HandleChange(form, setForm, event) {
  const { name, value } = event.target;

  setForm({
    ...form,
    [name]: value,
  });
}

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You just change decalre handleChange like this:

const handleChange = (event) => HandleChange(form, setForm, event);
about 4 years ago · Juan Pablo Isaza Relatório

0

Interesting approach. I suggest writing the helper function in the following way:


// Component 
[...]
return (
    <input
        type="text"
        name="firstName"
        value={form.firstName}
        onChange={event => setForm(assignValueToName(form, event))}
    />
)

// Helper
function assignValueToName(existing, event) {
    const { name, value } = event.target;
    
    return {...existing, [name]: value};
}
about 4 years ago · Juan Pablo Isaza Relatório

0

It will be better if you create your custom hook, like this:

This way you can use it directly as any other hook without creating custom logic or passing any parameters

//App.jsx

import useCustomForm from "./myCustomForm";

export default function App() {
  const [form, setForm] = useCustomForm({
    firstName: "qqq",
    lastName: "www"
  });

  return (
    <input
      type="text"
      name="firstName"
      value={form.firstName}
      onChange={setForm}
    />
  );
}


//myCustomForm.js

import { useState } from "react";

export default (defaultState) => {
  const [formState, setFormState] = useState(defaultState);

  const handleChange = ({target}) => {
    const { name, value } = target;
    setFormState({
      ...formState,
      [name]: value
    });
    console.log(formState);
  };

  return [formState, handleChange];
};
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