ReactJS handleClick

Thoughts on styles of handling Click events.

Everyone’s seen a simple React counter component:

function Counter1(props) {
  const [count, setCount] = useState(Number(props.initialCount) || 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(curr => curr - 1}>Decrement</button>
      <br />
      <button onClick={() => setCount(curr => curr + 1)}>Increment</button>
    </div>
    );  // end return
  } // end function

In the example above, the incrementing of the counter is done in-line inside the button. That’s nice and suitable for a simple implementation.

Then there comes a time when one separates out the event handling to a separate function, beneficial when more than the most simple processing is required:

function Counter2(props) {
  const [count, setCount] = useState(Number(props.initialCount) || 0);

  const handleClick = (event) => {
    // Note that value is incorrect: we need to set an id and / or
    // name on the button:
    if (event.target.value === "Increment")
      setCount(count => count + Number(value));
    else
      setCount(count => count - Number(value));
    };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Decrement</button>
      <br />
      <button onClick={handleClick}>Increment</button>
    </div>
    );  // end return
  } // end function

The above style is kind of a pain because one has to test inside the handleClick function which button was pressed and as buttons are added, complexity gets gnarly.

i.e. Did we set an id or a name? Because value will not work, that’s for input fields.

I think I’ve settled on the following method with minimal code in the handleClick function:

function Counter3(props) {
  const [count, setCount] = useState(Number(props.initialCount) || 0);

  const handleClick = (value) => {
    setCount(count => count + Number(value));
    };

 return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => handleClick(-1)}>Decrement</button>
      <br />
      <button onClick={() => handleClick(+1)}>Increment</button>
      <br />
      <button onClick={() => handleClick(+2)}>Increment by 2</button>
    </div>
    );  // end return
  } // end function

With the code above, the handleClick function does the updating (and anything else we want to do) without having to probe the value of the button clicked. We are not required to add a name or id to each button instance (not that it’s a bad idea to do so).

It’s easy to add new buttons as all the properties are contained within the button declaration.

By admin

Linux admin, JS / React / Python / Perl developer.