Home > Mobile >  react - not able to setValue for input box
react - not able to setValue for input box

Time:03-06

I am making 2 otp input in my application.

In Input.tsx, I am using react-otp-input for the otp functionality
if

    <OtpInput
      value={"abcde"}
      ...
      numInputs={5}
    />

The UI of react-otp-input will be

enter image description here

Now the problem is, when I try to change the value of otp, it throws error

Cannot set properties of undefined (setting 'value')

How can I fix it?

Input.tsx

import React, { useState } from "react";
import OtpInput from "react-otp-input";

type InputPropType = {
  value: string;
  setValue: (event: string) => void;
};

function Input(props: InputPropType): JSX.Element {
  const { value, setValue } = props;
  return (
    <OtpInput
      value={value}
      onChange={(e: string) => {
        setValue(e);
      }}
      numInputs={5}
    />
  );
}

export default Input;

App.tsx

import React, { useState } from "react";

import Input from "./Input";

export default function App() {
  type InputValueType = {
    id: number;
    value: string;
  };
  const [inputValues, setInputValues] = useState<Array<InputValueType>>([
    { id: 0, value: "" },
    { id: 1, value: "" }
  ]);

  const InputGroup = () => {
    let numOfInputs: number = 2;
    var rows: Array<any> = [];
    for (var i = 0; i < numOfInputs; i  ) {
      let inputValue: InputValueType = inputValues[i];
      rows.push(
        <Input
          key={inputValue.id}
          value={inputValue.value}
          setValue={(event: string) => {
            let inputValuesTemp = inputValues;
            inputValuesTemp[i]["value"] = event;
            setInputValues(inputValuesTemp);
          }}
        />
      );
    }
    return <>{rows}</>;
  };

  return (
    <div className="App">
      <InputGroup />
    </div>
  );
}

Codesandbox
Edit React Typescript (forked)

  • Related