Show value from input box by pressing the button

Goal:
Show the value of the element id ttt in console when you press the button "showvalue"

Problem:
The code won't work what part of the code am I missing?

Stackblitz:
https://stackblitz.com/edit/react-ts-sgczgk?

Info:
Newbie in React TS

Thank you!


import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

interface AppProps {}
interface AppState {
  name: string;
}

class App extends Component<AppProps, AppState> {
  constructor(props) {
    super(props);

    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  public textInput;

  focusTextInput() {
    console.log(this.textInput.value);
  }

  render() {
    return (
      <div>
        <input id="ttt" type="text" ref={this.textInput} />

        <input type="button" value="showvalue" onClick={this.focusTextInput} />
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));


this.textInput is not the HtmlInputelement its RefObject. If you want to access the underlying element you should be using this.textInput.current.value

Fixed fork

By the way, if you are using typescript you should be annotating your types correctly.

If you annotate your public textInput; as public textInput : RefObject<HtmlInputElement>; it would warn you that value doesn't exists on type RefObject<HtmlInputElement>