OsDev
OsDev

Reputation: 1252

How Refs works on react 0.14

I'm using a subrender approach (split the react component creation in a helpers methods) on my React 0.13 App like this. But I got an error:

Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method

So, how can manage my on the fly created react components that depend on the DOM to avoid to get fat my primary render method?

Any clue how to refactor that to the new approach in the 0.14 React version?

module.exports = React.createClass({
displayName: 'Typed',
render: function() {
    var _this = this;

    return (
      React.createElement("div", {
            style: {
                position: 'relative'
            },
            className: 'react-typeahead-container ' + _this.props.className},
        _this._renderInput(),
        _this._renderDropdown(),
        _this._renderAriaMessageForOptions(),
        _this._renderAriaMessageForIncomingOptions()
      )
    );
},
_renderInput: function() {
    var _this = this,
        state = _this.state,
        props = _this.props,
        inputValue = props.inputValue,
        inputValue = props.inputValue,
        className = 'react-typeahead-input',
        inputDirection = getTextDirection(inputValue);

    return (
        React.createElement("div", {
            style: {
                position: 'relative'
            },
            className: "react-typeahead-input-container"},
            React.createElement(Input, {
                ref: "input", //this does not works :(
                role: "combobox"
            )
        )
    );
},

Upvotes: 0

Views: 512

Answers (2)

Michelle Tilley
Michelle Tilley

Reputation: 159105

As this JSFiddle shows, the code you have above works (modified slightly so that it runs as written). There is a minor syntax error; the object containing the properties is missing a closing curly brace:

React.createElement(Input, {
    ref: "input", //this does not works :(
    role: "combobox"
) // <-- should be })

Upvotes: 2

Interactive Llama
Interactive Llama

Reputation: 780

From my understanding, ref should be a callback method that receives the referenced element. In this case, input. You can then store it in state or someone else and reference it. When it's valid, the referenced DOM node will have rendered.

Upvotes: 1

Related Questions