Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

104
Views
best way to have more than one function for react onClick events

I am working on a react button component that receives 1 function as prop to be executed on the onClick event

<Button onClick={() => console.log('hello')}>

this passes as

<button onClick={onClick}>
  Say hello
</button>

A new requirement has come, and we need to make a ping to our server to see how many users actually click on the button, but not every button will share this behaviour, what would be a clean way to add a new property and if it is present, execute both functions on click

<Button
    onClick={() => console.log('hello')}
    track=true
/>
<button
  onClick={() =>{
     if track trackClick()
     onClick()
  }}>
  Say hello
</button>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Shift everything into the parent component. Have a state that logs the counts of the buttons, and have your handleClick function call the first function and then, depending on the track information, update the count. Button1, in this example, will call doThing first and then update the count; Button2 will only call the function, and not update the count.

const { useEffect, useState } = React;

function Example() {

  const [ count, setCount ] = useState(0);

  useEffect(() => console.log(count), [count]);

  function doThing() {
    console.log('Thing');
  }

  function handleClick(e) {
    const { track } = e.target.dataset;
    doThing();
    if (track === 'true') setCount(count + 1);
  }

  return (
    <div>
      <Button
        handleClick={handleClick}
        text="Button1"
        track={true}
      />
      <Button
        handleClick={handleClick}
        text="Button2"
        track={false}
      />
    </div>
  );

}

function Button({ handleClick, text, track }) {
  return (
    <button
      onClick={handleClick}
      data-track={track}
    >{text}
    </button>
  );
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!