Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React ref is undefined after state change

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you want the ref persisted in your component’s instance data, use the useRef hook, not createRef.

const testInputRef = useRef<HTMLInputElement>(null);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading