Search code examples
javascriptreactjsinputonchange

React Input OnChange Field


I'm developing a React application. I've implemented an input field where users can enter values. However, I'm facing an issue with this input field. When users type, it displays intermediate values, such as "c," and "co," before showing the complete input, for example, "cow."

The reason I've stored the input as an array is that I have multiple instances of TextField generated in a loop, and I need to capture all the input values.

Here's the relevant code snippet:

  <TextField
    id="standard-basic"
    label="Standard"
    variant="standard"
    value={inputValue}
    onChange={(e) => {
      handleInputValue(e.target.value); 
    }}
  />


  const [inputValue, setInputValue] = useState([]); 

  const handleInputValue = (inputSubmitted) => {
    setInputValue([...inputValue, inputSubmitted]);

  };

My goal is to store multiple input values from different TextFields while ensuring that the input field displays only the final complete value, avoiding the display of intermediate values.

How can I achieve this behaviour? to handle multiple input values in a loop?


Solution

  • If you're trying to hold multiple states without overlap you can try a Map instead of an Array.

    const [inputValue, setInputValue] = useState(new Map())
    
    const handleInputValue = (id, inputSubmitted) => {
        setInputValue((p) => p.set(id, inputSubmitted))
    }
    
    // I know your implementation generates the TextField with a loop, but hardcoding 3 examples show the solution works on principle
    return (
        <TextField
            id="standard-basic"
            label="Standard"
            variant="standard"
            value={inputValue.get("standard-basic")}
            onChange={(e) => {
                handleInputValue(e.target.id, e.target.value)
            }}
        />
        <TextField
            id="standard-basic1"
            label="Standard"
            variant="standard"
            value={inputValue.get("standard-basic1")}
            onChange={(e) => {
                handleInputValue(e.target.id, e.target.value)
            }}
        />
        <TextField
            id="standard-basic2"
            label="Standard"
            variant="standard"
            value={inputValue.get("standard-basic2")}
            onChange={(e) => {
                handleInputValue(e.target.id, e.target.value)
            }}
        />
    )