Ad

React 0.14 - Using Refs Via FindDOMNode

- 1 answer

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;
Ad

Answer

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>
Ad
source: stackoverflow.com
Ad