Jacob Mason
Jacob Mason

Reputation: 1395

Unable to get property 'test' of undefined or null reference

I'm using ES6 with React and references don't seem to be playing ball.

export default class App extends React.Component {
  test() {
    console.log(React.refs.test);
  }
  render() {
    return (
      <div className="pure-g">
        <Nav>
          <NavButton onClick={this.test}>Test</NavButton>
        </Nav>
        <Map lat="53.15" lng="-0.5" zoom="9" />
        <SearchMenu ref="test" />
      </div>
    );
  }
}

Am I using refs incorrectly?

On another note, suddenly my onClick event is occurring when the page loads. Here's my button component.

export default class NavButton extends React.Component {
  render() {
    return (
      <li className="pure-menu-item" onClick={this.props.onClick}>
        <a className="pure-menu-link">{this.props.children}</a>
      </li>
    );
  }
}

Upvotes: 1

Views: 1127

Answers (2)

Jack
Jack

Reputation: 8941

Change your <NavButton /> to this

<NavButton onClick={this.test.bind(this)}>Test</NavButton>

Now this in your test function will be the component.

test() {
  console.log(this); //this will be your App Component
}

As for why your click is triggering on load I'd make sure you aren't actually calling the onClick function by accident:

this.props.onClick() instead of this.props.onClick

Upvotes: 1

James Allardice
James Allardice

Reputation: 165941

The refs are available on the component instance, not statically on React itself. Your ref should be referenced by this.refs.test rather than React.refs.test. This presents another issue with your example - the click event callback won't be invoked with the right context. You could work around that by binding the function passed through to button component:

export default class App extends React.Component {
  test() {
    console.log(this.refs.test);
  }
  render() {
    return (
      <div className="pure-g">
        <Nav>
          <NavButton onClick={this.test.bind(this)}>Test</NavButton>
        </Nav>
        <Map lat="53.15" lng="-0.5" zoom="9" />
        <SearchMenu ref="test" />
      </div>
    );
  }
}

Upvotes: 2

Related Questions