Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply useRef() in React TS?

Goal:
Get value from the textbox when you click on the button

Problem:
The value don't display in the console.

"Uncaught Error: Function components cannot have string refs. We recommend using useRef() instead"

How do you apply useRef() in this context?

Stackblitz
https://stackblitz.com/edit/react-ts-mcn4jd?file=index.tsx

Info:
*Newbie in react TS

Thank you!

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {

  function test() {
    // Get the value and display it at consol
    //var name = refs.mytext.value;
    
    var element = document.getElementById("ddddd");


    console.log(element);
  }

  return (
    <div className="App">
      <input type="text" id="ddddd" ref="mytext" />
      <button onClick={() => test()}>Add</button>
    </div>
  );
}

export default App;
like image 464
What'sUP Avatar asked Oct 24 '25 02:10

What'sUP


1 Answers

You could also use useRef<HTMLInputElement | null>(null) for better type support

import React, {useRef} from 'react';
import logo from './logo.svg';
import './App.css';


function App() {

  const mytext = useRef<HTMLInputElement | null>(null);

  function test() {
    // Get the value and display it at consol
    //var name = refs.mytext.value;
    
    var element = document.getElementById("ddddd");


    console.log(mytext.current?.value);
  }

  return (
    <div className="App">
      <input type="text" id="ddddd" ref={mytext} />
      <button onClick={() => test()}>Add</button>
    </div>
  );
}

export default App;
like image 156
epicmau5time Avatar answered Oct 26 '25 05:10

epicmau5time



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!