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'));

1 Answer 1

1

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"/>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.