HelloWorld1
HelloWorld1

Reputation: 14108

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;

Upvotes: 4

Views: 13053

Answers (3)

epicmau5time
epicmau5time

Reputation: 325

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;

Upvotes: 5

MWO
MWO

Reputation: 2806

In functional components you have to use ref={mytext} instead of ref="mytext"

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


function App() {

  const mytext = useRef<any>(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;

Upvotes: 0

anut
anut

Reputation: 481

You can use useRef to create a ref, and then pass that ref to the HTML using curly braces, like so

function App() {
  var mytext = useRef(null); // Create ref with no initial value
  function test() {
    var name = mytext?.current?.value; // Get ref value

    console.log(name);
  }

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

Upvotes: 0

Related Questions