Home > database >  Why does `React.createElement()` create an object?
Why does `React.createElement()` create an object?

Time:12-12

I'm learning React and I thought that React.createElement(type, [props], [...children]) was just a method that encapsulates the DOM methods.

So, this React example: React.createElement('h1', {className: 'greeting'}, 'Hello, world!') would execute (something like) these statements:

const element = document.createElement('h1');
element.setAttribute('class', 'greeting');
document.createTextNode('Hello World');

However, I just read in their documentation that this method returns this object:

// Note: this structure is simplified
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};

I also tried to search for the contents of that function, but from the minified version I found, it refers mostly to the creation of that object. Meanwhile, I couldn't see anything referring to the DOM methods.

Does anyone have more information about why it creates an object, and how does it communicate with the HTML?

CodePudding user response:

You can read about reconciliation, read the Fiber architecture guide, and view the React DOM source for a very comprehensive understanding.

Essentially, React DOM acts as a mediator to reconcile the state of the DOM with those objects.

  • Related