What's the difference between `React.createElement (...)` and `new MyComponent ()`?
Introduction: I'm a little confused by the reaction. I've seen articles that say React components are just functions that get the props and render of the virtual DOM. However, I can see that they are full blown stateful monsters and I have not found a way to treat them as functions.
Question: Why React.createElement
does every use of a React component end in ? Why can't I use new MyComponent()
this instead? It looks pretty similar when I do it in DevTools. Why is it React.createElement
needed at all, given that components are created using React.createClass
? This looks like overkill to me.
Edit: This looks relevant: https://gist.github.com/sebmarkbage/ae327f2eda03bf165261
Edit # 2: This is related, but not a duplicate of React.Component vs React.createClass , this question asks about creating classes. I am not asking about creating new component classes, I am asking about instantiating (elements) of these classes.
source to share
I think I found the answer here :
In React 0.12, we're making a major change in how React.createClass (...) and JSX work.
(...)
Currently
var Button = React.createClass(...)
doing two things. This creates a class and a helper function for creating ReactElements. this is what is equivalent to this:
class ButtonClass { } function ButtonFactory(...args) { return React.createElement(ButtonClass, ...args); } module.exports = ButtonFactory; ```
You will then access this in the consuming component by calling ButtonFactory.
var Button = require('Button'); class App { render() { return Button({ prop: 'foo '}); // ReactElement } }
Conceptually, this is the wrong model. The original component should not be responsible for the output of the application.
There are several problems with this:
- ES6 classes cannot be directly exported, they need to be wrapped.
- There is no convenient way to access the actual class and it confuses the one you are using.
- Static methods are wrapped in helpers, which are not a real function. As a convenience.
- Auto mocking destroys the factory, so there is no way to check the rendering result without disabling mocking.
- Factories can be wrapped with other factories that return something other than ReactElements. Testing and optimization is not possible.
- Languages with specialized functions for manipulating objects should defer to React instead of using inline functions.
source to share