John D
John D

Reputation: 138

How to get value of an input text in reactjs version 16.13.1

i'm new in reactjs. i was reading a documentation how to get an input value. But i'm still getting an undefine error. This is what i did.

class Test extends React.Component{
  constructor(props){
    super(props)
    this.inputRef = React.createRef()
  }
  clickHandler(){
    console.log(this.inputRef)
  }
  render(){
    return(
      <div>
        <input type="text" ref={this.inputRef}/>
        <button onClick={this.clickHandler}>click Me</button>
      </div>
    )
  }
}
ReactDOM.render(<Test />, document.getElementById('root'));

Upvotes: 1

Views: 138

Answers (1)

Zachary Haber
Zachary Haber

Reputation: 11027

Your issue was that you didn't bind the clickHandler to your component.

The easiest way is to use an arrow function instead of a class method:

  clickHandler=()=>{
    console.log(this.inputRef)
  }

Otherwise in your constructor, you need to bind the clickHandler manually:

  constructor(props){
    super(props)
    this.inputRef = React.createRef()
    this.clickHandler = this.clickHandler.bind(this);
  }

Here's an example of using an arrow function (which binds automatically)

class Test extends React.Component{
  inputRef = React.createRef()
  clickHandler=()=>{
    console.log(this.inputRef.current.value)
  }
  render(){
    return(
      <div>
        <input type="text" ref={this.inputRef}/>
        <button onClick={this.clickHandler}>click Me</button>
      </div>
    )
  }
}
ReactDOM.render(<Test />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"/>

Upvotes: 1

Related Questions