Kayote
Kayote

Reputation: 15627

Understanding React Behind The Scene

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?

Upvotes: 2

Views: 1402

Answers (2)

damio
damio

Reputation: 6301

  1. Correct. foo is like a constructor but under the scene it uses React.createElement(foo, null) when you type <foo />.

  2. this is gonna refer to the instance of bar in this case, not the constructor.

  3. To keep multiple instances of foo, just keep them in variables like usual.

    a = React.createElement(foo, null); //or a = <foo />
    b = React.createElement(foo, null); //or b = <foo />

PS: Convention is to CamelCase the class names (foo becomes Foo)

Upvotes: 0

Michelle Tilley
Michelle Tilley

Reputation: 159105

  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.

Upvotes: 1

Related Questions