You're probably getting this warning because you're accessing methods on a component before it gets mounted. This will be soon be an unsupported use case.
The component that gets created by invoking the convenience constructor MyComponent(props, children)
or using the JSX syntax <MyComponent />
is not guaranteed to be the instance that actually gets mounted. It's a description of what the actual mounted instance should look like.
Anti-pattern:
The component also doesn't have access to state or other important information such as the final props. As a consequence you shouldn't be calling custom methods on this object.
var MyComponent = React.createClass({
customMethod: function() {
return this.props.foo === 'bar';
},
render: function() {
}
});
var component = <MyComponent foo="bar" />;
component.customMethod(); // invalid use!
Correct Usage:
The upgrade path is to convert these methods to static methods and invoke them with the necessary parameters.
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
// If you know the type, you can just invoke it directly
MyComponent.customMethod('bar'); // valid
// If you don't know the type of the component, you can use the .type property.
// This is useful if the component is passed into you.
var component = <MyComponent foo="bar" />;
...
component.type.customMethod(component.props.foo); // valid
Access to the Mounted Instance:
If you need access to the real instance that is mounted you can use either the return value of React.renderComponent(...)
or refs in callbacks.
var MyComponent = React.createClass({
customMethod: function() {
return this.props.foo === 'bar';
},
render: function() {
}
});
var realInstance = React.renderComponent(<MyComponent foo="bar" />, root);
realInstance.customMethod(); // this is valid
var Container = React.createClass({
handleClick: function() {
this.refs.component.customMethod(); // this is also valid
},
render: function() {
return (
<div onClick={this.handleClick}>
<MyComponent foo="bar" ref="component" />
</div>
);
}
});
I'm getting this warning by calling a method on a custom mixin from within my component's
render()
method. Shouldn't mixin methods be accessible by the time I'm rendering? If not, then what is the point of a mixin?