how to shrink code in react.js with similar functionality

Viewed 34
  import { AiOutlineArrowDown, AiOutlineArrowUp } from "react-icons/ai";
  import { useState } from "react";
  const Vote = () => {
    const [num, setnum] = useState({
      num1: 0,
      num2: 0,
      num3: 0,
    });
    const valuechanger = (value, action) => {
      setnum((i) => {
        return {
          ...i,
          [value]: action === "down" ? num[value] - 1 : num[value] + 1,
        };
      });
    };
    const v1 = num.num1;
    const v2 = num.num2;
    const v3 = num.num3;
    var value1 = (
      <>
        <button disabled={v1 <= 0} onClick={() => valuechanger("num1", "down")}>
          <AiOutlineArrowDown />
        </button>
        {v1}
        <button onClick={() => valuechanger("num1", "up")}>
          <AiOutlineArrowUp />
        </button>
      </>
    );
    var value2 = (
      <>
        <button disabled={v2 <= 0} onClick={() => valuechanger("num2", "down")}>
          <AiOutlineArrowDown />
        </button>
        {v2}
        <button onClick={() => valuechanger("num2", "up")}>
          <AiOutlineArrowUp />
        </button>
      </>
    );
    var value3 = (
      <>
        <button disabled={v3 <= 0} onClick={() => valuechanger("num3", "down")}>
          <AiOutlineArrowDown />
        </button>
        {v3}
        <button onClick={() => valuechanger("num3", "up")}>
          <AiOutlineArrowUp />
        </button>
      </>
    );
  
    return (
      <>
        {value1}
        {value2}
        {value3}
      </>
    );
  };
  
  export default Vote;

In the upper code I have created two voting areas having increament and decreament functionality. how I can shrink this code as values 1,2,3 in code are pretty similar(The main goal is shrinking)

the valuechanger function returns a decrease or increase in value if the parameter of up or down matches the intial parameter. I have also used the react icons { AiOutlineArrowDown, AiOutlineArrowUp }

If can shrink it in any way please help me

0 Answers
Related