how to access methods of an instance of a React component?

- 1 answer

Ad

Is there a way to call the methods that a React component defines internally?

I understand generally we want to be passing values around declaratively with props/data etc. However I am using some component libraries that have internal useful methods.

eg

var field = <AutoComplete/>;
field.setValue("ready");  // doesn't work

eg this method https://github.com/callemall/material-ui/blob/master/src/auto-complete.jsx#L244-L248

in material-ui AutoComplete component.

Ad

Answer

Ad

You can not do this with virtual dom, since virtual dom is just a description of components to be created(actual component instance will be created or updated only when rendering).

But you can access component instances inside your react component after rendering using refs:

var Test = React.createClass({
  getInitialState: function(){
    return {value:0};
  },
  setValue: function(value){
    this.setState({value:value});
  },
  render: function() {
    return <div>Value {this.state.value}</div>;
  }
});

var App = React.createClass({
  render: function() {
    return <div>
      <Test ref="test"/>
      <button onClick={()=>this.refs.test.setValue(1)}>1</button>
      <button onClick={()=>this.refs.test.setValue(2)}>2</button>
      <button onClick={()=>this.refs.test.setValue(3)}>3</button>
    </div>;
  }
});

var mountNode = document.getElementById('app');

ReactDOM.render(<App name="John" />, mountNode);

jsbin with code above: http://jsbin.com/kitehujaje/1/edit?js,output

Ad
source: stackoverflow.com
Ad