- Mostly we use the JSX markup inside our component.
- But, React also provide the function `createElement()` to create differnt elementos without using the JSX.
- It is little bit complicated and we need to write more code.
E.g. Below are two examples:
- In first example we use the
JSX
. - And, In second we’ll use the
createElement()
.
1) Using JSX:
import { createElement } from 'react';
const App = () => {
return (
<h1 id="first">Heading 1</h1>
)
}
export default App;
2) Using `createElement()`
import { createElement } from 'react';
const App = () => {
return (
createElement(
'h1',
{
'id': 'first',
},
'Heading 1'
)
)
}
export default App;
Here, The function `createElement()` accepts 3 parameters:
- First argument is tag name. In our example we have pass the `h1` as first parameter to create a `<h1>` tag.
- Second argument is attribute object. In our example we pass the object `{ ‘id’: ‘first’ }` to set the **ID** attribute with value **first** to our `<h1>` tag.
- Third argumentn is the markup. In our example we pass it as `Heading 1` which is the text of our `<h1>` tag.
NOTE: We can pass the another createElement() as a 3rd argument to create nested elements.
E.g.
const App = () => {
return (
createElement(
'div',
{
'id': 'wrapper',
},
[
createElement(
'h1',
{
'id': 'one',
},
'Heading One'
),
createElement(
'h2',
{
'id': 'two',
},
'Heading Two'
),
]
)
)
}
Here, We have created 1 **div** tag with id **wrapper** and inside it created `<h1>` and `<h2>` tags with ID **one** and **two** respectively.
Lets check how it is more easys with JSX format.
const App = () => {
return (
<div id="wrapper">
<h1 id="one">Heading One</h1>
<h2 id="two">Heading Two</h2>
</div>
)
}