2

Anyone know what the null is in this line:

React.DOM.p(null, message); 

I'm aware it's a convenience wrapper around createElement, i.e.

ReactElement createElement( string/ReactClass type, [object props], [children ...] ) 

but am struggling to understand why the type is null.

The same would go for this line here:

React.DOM.div(null, 'Hello World!') 

1 Answer 1

6

These functions are commonly referred to as factories meaning they are functions that generate ReactElements with a particular type property.

This is roughly how these factories are created under the hood:

function createFactory(type) { return React.createElement.bind(null, type); } 

Which returns React.createElement as a bound function with this bound to null and type bound to whatever was passed in, allowing you to create shorthand instantiation functions for your elements:

// create a function that creates React <div> elements let div = createFactory('div'); // create two divs using the div factory function let div1 = div({ /* some props */ }, 'Div 1'); let div2 = div({ /* some props */ }, 'Div 2'); 

React already comes with built-in factories for common HTML tags such as div, li etc, which you have in your question.


but am struggling to understand why the type is null.

Considering all of the above, when you look at one of your examples:

React.DOM.div(null, 'Hello World!') 

The following happens:

React.DOM.div is just a factory function that under the hood passes 'div' as the first argument to React.createElement, which is the type, and everything else gets passed as the remaining arguments.

Basic idea:

// the function is created as a factory React.DOM.div = createFactory('div'); // and used to create a <div> element var myDiv = React.DOM.div(null, 'Hello World'); 

This value of div as the first argument was setup in a similar manner as i've shown above whenever this factory was created.

Therefore, null in your case is just the props object, not the type. Type is bound to be div through the factory, meaning props is the first argument and 'Hello World!' string is the children argument.

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

2 Comments

Great answer. In the last paragraph, I assume you mean 'div' is passed as the first argument to createFactory
Thanks, glad to help. Actually I do not think that, i've made an edit to clarify :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.