2

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.

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.