Home > Software engineering >  Execute two functions at onClick with React
Execute two functions at onClick with React

Time:09-30

I currently have this table, where when the user clicks the button it toogles the "editForm" state, but I also want to change the idColab state when the user clicks the button, how can I accomplish that?

obs: The ID is passed as a parameter.

const [editForm, setEditForm] = useState(false)
const [idColab, setIdColab] = useState("")


const exibirForm = () => {
        setEditForm(!editForm)
}

const setIdColab = (id) => {
        idColab = id
}

The ID comes from this mapping:

const renderTable = () => {
        return data.map((colaborador, idx) => {
            const {id, nome, matricula, funcao, tipo_acesso, cpf} = colaborador

            return (
                <tr>
                    <td className='data-cell'>{nome}</td>
                    <td className='data-cell'>{matricula}</td>
                    <td className='data-cell'>{newFuncao}</td>
                    <td className='data-cell'>{newAcesso}</td>
                    <td className='data-cell'>{cpf}</td>
                    <td className='data-cell'>{id}</td>
                    <td className='btn-cell'><input className="edit-btn" type="submit" value="Editar" onClick={exibirForm(id)} /></td>
                </tr>
            ) 
        })
    }

CodePudding user response:

Option 1

By adding the code within the called function:

const exibirForm = () => {
  setEditForm(!editForm)
  setInput({ idColab: "1234"  });
}

Option 2

By creating a function that calls more functions

const masterFunction = () => {
  function1();
  function2();
  // ... more functions ...
}

Or even more compact:

<input onClick={() => { function1(); function2(); }} />

CodePudding user response:

Create a parent function that calls both functions in it and pass the parent function to your event listener .

  • Related