Home > Net >  how to get last value from user input event and push into array react.js
how to get last value from user input event and push into array react.js

Time:09-16

I have an Input component that creates as many input tags as needed based on JSON data.

I'm using the onChange method in the input tag and passing the event into a function "handleChange" using contextAPI to record the values in a different component.

I'm trying to then push that value into an array but when doing so it pushes every event the user presses let's say the user types in 450, when pushing array it comes out as ["4", "45", "450], how would I get the last value user puts?

Input component:

  const { handleChange } = useContext(FormContext);

  return (
    <input
      id={`input-text${id}`}
      onChange={(e) => handleChange(id, e)}
      style={{
        position: "absolute",
        top: `${fieldsPosX}px`,
        left: `${fieldsPosY}px`,
        background: "blue",
        border: "black",
        height: "30px",
        maxWidth: "70px",
        width: "100%",
        zIndex: "40",
        color: "#fff",
        textAlign: "center"
      }}
      maxLength={maxLength}
      type={"text"}
    />
  );
}

export default Input;

handleChange function:

  const handleChange = (id, e) => {
    console.log(e.target.value);

    answers.push(e?.target?.value);
  };

Current output: ["4", "45", "450"]

Expected output: ["450"]

CodePudding user response:

Maybe you can use a submit <button> as a trigger to push your user input to the array instead of just using the <input>. The onChange event track every change in the <input>, so every single change in there will trigger the handleChange() function. That's why everytime the user input a character it will trigger the handleChange() function.

CodePudding user response:

[answers, e?.target?.value] 

use this instead of answers.push

  • Related