Uncaught ReferenceError: txtNoteRef is not defined - useRef - reactJS

Viewed 191

I am trying to create simple react js app, below is my code snippet(Notes.tsx file)

import React, { createRef, useRef } from 'react';
function NotesEditor(props: any) {
    const txtNoteRef = useRef<HTMLInputElement>(null);
    return (
        <div className={"row"}>
            <div className="col-md-6">
                <div className="form-group">
                    <input type="text" ref={txtNoteRef} id="txtNote" className="form-control"></input>
                </div>
            </div>
            <div className="col-md-6">
                <input type="button" className="btn btn-primary" value="Save Note" onClick={handleSaveNote}></input>
            </div>
        </div>
    );
    function handleSaveNote(event: any) {
        debugger
    }
}
export default NotesEditor;

can someone please explain why I am getting error Uncaught ReferenceError: txtNoteRef is not defined whenever I am trying to access it in method handleSaveNote() or how can I use useref properly? below is the screenshot of the error.

enter image description here

1 Answers

i was able to resolve this error by changing line const txtNoteRef = useRef<HTMLInputElement>(null); to const txtNoteRef = useRef<any>(); and it worked!!!

import React, { createRef, useRef } from 'react';
function NotesEditor(props: any) {
const txtNoteRef = useRef<any>();
return (
    <div className={"row"}>
        <div className="col-md-6">
            <div className="form-group">
                <input type="text" ref={txtNoteRef} id="txtNote" className="form-control"></input>
            </div>
        </div>
        <div className="col-md-6">
            <input type="button" className="btn btn-primary" value="Save Note" onClick={handleSaveNote}></input>
        </div>
    </div>
);
    function handleSaveNote(event: any) {
        debugger
    }
}
export default NotesEditor;
Related