Snow Crash Snow Crash - 3 months ago 8x
Javascript Question

React.DOM.p(null, message) - explain null

Anyone know what the

is in this line:

React.DOM.p(null, message);

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

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

but am struggling to understand why the

The same would go for this line here:

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


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 return 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
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.