Ad

Understanding React Behind The Scene

- 1 answer

Im trying to get my head around 'Components' in React.

I have a few questions so I thoughts I'd SO community is the best place to ask them.

1 - When we do this:

var foo = React.createClass ({
...
});

Console.log tells me that this is a constructor. So when we do <foo />, we are creating an instance (object) of foo, correct?

2 - Im particularly getting confused by this, here is the example:

var bar = React.createClass ({
    render = function () {
        if (this.props.xyz) {
          ...
        }
    }
});

Now <bar /> is a child component of foo. When bar instance is instantiated, this should refer to 'bar', shouldn't it? Why is it still referencing foo?

3 - Suppose I created multiple instaces of <foo />. How do we store reference to each particular object?

Ad

Answer

  1. Foo is a component class, and <Foo /> creates what's called a React element, which is a lightweight description of which component class you want React to render; <Foo /> actually gets turned into React.createElement(Foo), which returns a simple object. It does not actually create an instance at that time. React looks at these elements during its reconciliation phase and instantiates components that it needs to behind the scenes.

    See React (Virtual) DOM Terminology for more information about the terminology.

  2. Bar is only a child component of Foo if Foo returns a React element describing Bar from its render method. In any case, this refers to the current Bar component, and this.props.xyz refers to the props of the current Bar component. For example, if you did

    var Foo = React.createClass ({
      render: function() {
        return <Bar xyz="test" />;
      }
    });
    

    Then inside Bar, this.props.xyz will be the value "test", which was passed to Bar (just like an argument to a function) from its parent, Foo.

  3. You can use refs to access component instances if you really need to, but especially when beginning, I recommend against this. It's usually not the correct way to get things done in React, and you should only need to access component instances in relatively rare instances.

Ad
source: stackoverflow.com
Ad