Home > Enterprise >  Using a ternary operator incide a react event Listener callback function
Using a ternary operator incide a react event Listener callback function

Time:10-01

I am wondering why using a ternary operator inside an event listener callback function does not work however the complete if statement works perfectly. Got en error message with the first code('Expected an assignment or function call and instead saw an expression.')

import React, { useState } from "react";

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

  const addCount = () => {
    setCount(count   1);
  };

   const removeCount = () => {
    count > 0 ? setCount(count - 1) : null;
  };

  return (
    <>
      <h1>Counter : {count}</h1>
      <button onClick={addCount}>Add</button>
      <button onClick={removeCount}>Subtract</button>
    </>
  );
};

export default App;

However, this works

import React, { useState } from "react";

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

  const addCount = () => {
    setCount(count   1);
  };

  const removeCount = () => {
    if (count > 0) {
      setCount(count - 1);
    }
  };

  return (
    <>
      <h1>Counter : {count}</h1>
      <button onClick={addCount}>Add</button>
      <button onClick={removeCount}>Subtract</button>
    </>
  );
};

export default App;

CodePudding user response:

Expected an assignment or function call and instead saw an expression. (@typescript-eslint/no-unused-expressions)eslint

Ternary operators are basically used to assign a variable a value based on a condition.

The code is running the same way in both of the implementations but the eslint must be showing this error because of how ternary is used which is as per your eslint settings.

CodePudding user response:

It's a non sense to use the ternary operator here. As it been said, it's usually used for assignement (e.g. const a = isTrue ? 1 : 2).

But in your example, you can use the && operator like this :

count > 0 && setCount(count - 1)

(if the left-hand expression is true, so the right-hand function will be called)

  • Related