1

I am trying to access an input field on the click of button using refs. The syntax that I have written works fine in ComponentDidMount but gives the following error on click of the button. Uncaught TypeError: Cannot read property 'refs' of null.

"use strict"

import React from 'react'
import ReactDOM from 'react-dom'

class Dashboard extends React.Component {
    componentDidMount() {
        console.log("in component did mount", ReactDOM.findDOMNode(this.refs.Url))
    }
    shortenURL() {
        console.log("in function", ReactDOM.findDOMNode(this.refs.Url)) //Gives error: Uncaught TypeError: Cannot read property 'refs' of null
    }
    render() {
        return (
          <div className="container">
            <form>
          <div className="create-board">
            <div className="board-header">
              <h3 className="board-header-h3">URL Shortener</h3>
            </div>
            <div className="control-group txt-control">
                <div className="form-group">
                  <label className="control-label" htmlFor="inputURL">Enter your long URL here</label>
                  <input type="text" ref="Url" className="form-control" placeholder="Enter Your Long URL here"></input>
              </div>
              <div className="control-group but-control">
                <div className="controls">
                  <button className="btn  btn-info" type="button" onClick={this.shortenURL}>Shorten</button>
                </div>
              </div>
            </div>
          </div>
        </form>
          </div>
        )
    }
}
export default Dashboard;
Nikita Jajodia
  • 4,220
  • 3
  • 21
  • 29

2 Answers2

0

It's because you lose the context for this when a user clicks. Try this instead:

<button className="btn btn-info" type="button" onClick={this.shortenURL.bind(this)}>Shorten</button>
Thomas
  • 1,360
  • 1
  • 9
  • 15
0

You can read more about this issue in a discussion on React Github. Basically ES6 methods don't auto-bind to this. You can either use bind as Thomas mentioned, or you can use the succinct Arrow function -

onClick={(e) => this.shortenURL()}

hazardous
  • 10,627
  • 2
  • 40
  • 52