Reputation: 33
I'm currently trying to learn React, and maybe I'm just sleepy and missing something, but I need to ask:
In this code example(from React's "Getting Started" pages), why is "World" printed? From what I can see, where this.props.name is passed, the function is looking for children, not picking up additional text input. At least that's how I interpret the docs re: React.createElement.
This code is "working as intended", printing "Hello World"...but can anyone tell me exactly why it works? I would expect to just see "Hello", and maybe a console error about "World" not being defined. To whoever answers, thank you in advance for your explanation. ;)
var Hello = React.createClass({
displayName: 'Hello',
render: function() {
return React.createElement("div", null, "Hello ", this.props.name);
}
});
ReactDOM.render(
React.createElement(Hello, { name: "World"}),
container
);
Upvotes: 3
Views: 135
Reputation: 36965
The React.createElement
function takes the type of element to be created (if a string is passed it's an HTML element name, but it can also be a reference to a ReactClass
), then a props
object, then an undetermined number of children as the following arguments.
When you invoke
React.createElement(Hello, { name: "World"})
you are passing Hello
as the React Class to be instantiated and an object { name: "World"}
as the props
, which is then available as this.props
in all the methods of Hello
, including the render
method.
Then the Hello
element (class) calls createElement
again:
React.createElement("div", null, "Hello ", this.props.name)
here, "div"
is the type of HTML element to be created, props
are null, and both "Hello "
and this.props.name
are children to be created, in this example simple strings, the first one being a literal string, the second one is a reference to a key in the props
object passed above.
So what you have probably missed is that you can pass any number of arguments to the createElement
method and all the arguments starting with the 3rd will be rendered as sibling elements.
Upvotes: 1
Reputation: 3526
As you can see, inside the render function, there's an additional parameter passed into the createElement
function.
First parameter is the component class which you would like to instantiate and second are the props. Here we have a name
prop defined with a value of "World"
.
Since the Hello
component takes in the prop called name
, it will render it out along with the "Hello "
that the component is told to contain. It is a simple div
element.
Here you can see the parameters defined and explained for the createElement
function that React exposes.
Namely:
React.createElement("div", null, "Hello ", this.props.name);
Element Type - div
Props - null
Two children - "Hello "
and this.props.name
(which is "World"
)
Upvotes: 2