landunder
landunder

Reputation: 382

React lifecycle method on createElement()

I want to store my components into an array to get further access to methods like addChild. I can't find a suitable lifecycle method to store the component. Right now I'm abusing the getInitialState function.

components = {};

function Component(){
  return React.createClass({
    getInitialState : function({
      components[this.props.id] = {addChild: this.addChild}; 
      return child : [];
    }),
    addChild(child){
      this.state.children.push(child);
      this.setState({
        children : this.state.children
      });

    ...
  });
}

This function triggers only if the component is rendered. Is there a lifecycle function that is executed after the creation of a component with createElement()?

Or is there a better way to store the component to get further access to methods?

Upvotes: 1

Views: 417

Answers (1)

Quentin Roy
Quentin Roy

Reputation: 7887

You can get the instance of an element once it is rendered by providing a callback to the ref property of this element.

Here is how you could use it (I assumed you have a JSX and ES6 transpiler):

var instances = {};
const storeInstance = (i) => instances[i.props.id] = i;

var foo1 = (<Hello id="foo1" ref={storeInstance}/>);
var foo2 = (<Hello id="foo2" ref={storeInstance}/>);
var foo3 = (<Hello id="foo3" ref={storeInstance}/>);

Here is a live version.

However, I would advise caution with such method as it can very rapidly become an anti-pattern. It is usually easier and more elegant to use the bottom-up re-render React mechanism. You just update the element's property from its parent and let React do the rest.

Upvotes: 2

Related Questions