Home > database >  Adding Value in an array by click in a "button"
Adding Value in an array by click in a "button"

Time:01-11

I have an array. That has a value of Objects. There are 3 values in 1 Array for 1 Object.

It's a ReactJS project.

For example like that

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5],

]);

Now I have a button.

My question is "How or What function I can add to my button so that it will change the Middle value[1] of each array"

For example: after clicking the button I want to add [ - 0.5 * 2 ] in the middle value.

!!! Click !!!

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

!!! Click [2nd time] !!!

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3 - 0.5 * 2, 3],
[4, 4 - 0.5 * 2, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

!!! Click [3rd time] !!!

const x = useMemo(() => [

[1, 1 - 0.5 * 2, 1],
[2, 2 - 0.5 * 2, 2],
[3, 3 - 0.5 * 2, 3],
[4, 4 - 0.5 * 2, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

and so forth.

CodePudding user response:

import { useState } from 'react';

export default function DemoPage() {
  const [positions, setPositions] = useState([
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3],
    [4, 4, 4],
    [5, 5, 5],
  ]);
  const targetIndex = positions.length - 1;

  const clickHandle = () => {
    const nextPositions = positions.map((items, index) => {
      if (targetIndex === index) {
        // If there are more array items, you can use `.map` .
        // return items.map((value) => value * 2);
        return [items[0], (items[1] - 0.5) * 2, items[2]];
      }
      return items;
    });

    setPositions(nextPositions);
    console.log('positions :>> ', positions);
  };
  return (
    <div>
      <p>position is { positions[targetIndex].join(',') }</p>
      <button type="button" onClick={clickHandle}>Click</button>
    </div>
  );
}

To update the array see here: https://beta.reactjs.org/learn/updating-arrays-in-state#replacing-items-in-an-array

It is recommended to use "use-immer", which makes data updates easier.

use-immer: https://www.npmjs.com/package/use-immer

  • Related