4

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;
HelloWorld1
  • 13,688
  • 28
  • 82
  • 145

3 Answers3

5

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;
epicmau5time
  • 316
  • 3
  • 7
0

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>
  );
}
anut
  • 481
  • 1
  • 11
  • I get a error in VS code saying " > 10 | TS2531: Object is possibly 'null'. at "var name = mytext.current.value;" – HelloWorld1 Jan 16 '22 at 18:44
  • It is warning you that mytext.current might be null; use `mytext?.current?.value` instead. – anut Jan 16 '22 at 18:47
0

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;
MWO
  • 2,627
  • 2
  • 10
  • 25