How to forward input ref to a function by onClick button

556 Views Asked by At

I am trying to forward input ref text/string data to a function by clicking the button. but I cant forward or pass the data to my function by using button

--questionRef is my ref input data

--answerQuestion is my function

<input ref={questionRef} size="80"></input>
 <button type="button" onClick={answerQuestion} >Enter</button>

I tried to use my button for forward the questionRef input to answerQuestion function but it failed. Also it works when I click enter on my keyboard

1

There are 1 best solutions below

1
On

Pretty simply:

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={() => answerQuestion(questionRef)}
   >Enter
   </button>

Eventually, you can include also the onClick event to your function, depends on what you need to do with it:

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={(e) => answerQuestion(questionRef, e)}
   >
     Enter
   </button>

Based on Junius L. comment:

const questionRef = useRef()
const answerQuestion = () => {
      doSomethingWithRef(questionRef) // questionRef is accessible in whole component scope
}

<input ref={questionRef} size="80"></input>
   <button 
        type="button" 
        onClick={answerQuestion}
   >Enter
   </button>