import { StepData } from "@/components/steptree/StepData";
import { Input } from "@material-tailwind/react";
import { RegisterValidateHandler } from "./DataHandler";
import React, { useCallback } from "react";
export function StartDataHandler({stepData, validator} : {stepData: StepData, validator : RegisterValidateHandler}) {
const [error, setError] = React.useState("");
let testInputRef = React.createRef<HTMLInputElement>();
validator(() => {
//this arrow function gets called whenever I click a certain
//button
console.log("testInputRef value: ", testInputRef.current?.value);
if (testInputRef.current?.value == "test") {
return true;
} else {
//once setError is called, testinputRef.current is
//undefined forever
setError("testInputRef is empty");
return false;
}
});
return (
<div>
{error != "" && <h2>{error}</h2>}
<input ref={testInputRef} type="text" placeholder="test start"/>
{/* <Input ref={testInputRef} label="test start"/> */}
</div>
)
}
The arrow function passed to validator() is called externally after clicking on a button.
When I click the button and the input value is "test" then it always keeps the latest value of the input element. Once setError is called (value is not ‘test’) then testInputRef.current is undefined forever no matter how often I change the input value and click the button.
>Solution :
If you want the ref persisted in your component’s instance data, use the useRef hook, not createRef.
const testInputRef = useRef<HTMLInputElement>(null);