Why would I use React.createElement() instead of JSX?

Question

Why would I use React.createElement() instead of JSX?

Answer

We would use React.createElement() instead of JSX when we do not want to set up compilation for our project, which the use of JSX requires!

9 Likes

There is a minor typo in the Answer section. There is a misplaced I in React.createElementI().

I have been enjoying your React Q&A posts. Thank you.

8 Likes

I hope that the compilation/setup for the project is covered.

2 Likes

Why it need to add letter I?

There was a typo in the answer by aubsrey, fieryneuron was so kind to inform us about it. The I was the typo :wink:

1 Like

In the exercise we had:

The following JSX expression:

const h1 = <h1>Hello world</h1>;

can be rewritten without JSX, like this:

const h1 = React.createElement(
  "h1",
  null,
  "Hello, world"
);

Shouldn’t we have used parentheses, when declaring with JSX, like so instead?

const h1 = (
<h1>Hello world</h1>
);

Been a while since I done react, but I believe parentheses are only needed for multi-line JSX expression. Single lines can be written without parentheses.

4 Likes

what is null in the React.createElement? What does it represent?

If you check the documentation:

https://reactjs.org/docs/react-api.html#createelement

you can see the second parameter is props, so null means we don’t pass any properties down to child component.