createElement
createElement
memungkinkan Anda membuat elemen React. Ini berfungsi sebagai alternatif untuk menulis JSX.
const element = createElement(type, props, ...children)
Reference
createElement(type, props, ...children)
Panggil createElement
untuk membuat elemen React dengan parameter type
, props
, dan children
.
import { createElement } from 'react';
function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello'
);
}
Lihat lebih banyak contoh lainnya di bawah ini.
Parameters
-
type
: Argumenttype
harus berupa tipe komponen React yang valid. Misalnya, bisa berupa string nama tag (seperti'div'
atau'span'
), atau komponen React (fungsi, kelas, atau komponen khusus sepertiFragment
). -
props
: Argumenprops
harus berupa objek ataunull
. Jika Anda mengopernull
, itu akan diperlakukan sama seperti objek kosong. React akan membuat elemen dengan props yang cocok denganprops
yang telah Anda oper. Perhatikan bahwaref
dankey
dari objekprops
Anda adalah spesial dan tidak akan tersedia sebagaielement.props.ref
danelement.props.key
padaelement
yang dikembalikan. Mereka akan tersedia sebagaielement.ref
danelement.key
. -
optional
...children
: Nol atau lebih simpul anak. Mereka bisa berupa simpul React apa saja, termasuk elemen React, string, angka, portal, simpul kosong (null
,undefined
,true
, danfalse
), dan array simpul React.
Returns
createElement
returns a React element object with a few properties:
type
: Thetype
you have passed.props
: Theprops
you have passed except forref
andkey
. If thetype
is a component with legacytype.defaultProps
, then any missing or undefinedprops
will get the values fromtype.defaultProps
.ref
: Theref
you have passed. If missing,null
.key
: Thekey
you have passed, coerced to a string. If missing,null
.
Usually, you’ll return the element from your component or make it a child of another element. Although you may read the element’s properties, it’s best to treat every element as opaque after it’s created, and only render it.
Caveats
-
You must treat React elements and their props as immutable and never change their contents after creation. In development, React will freeze the returned element and its
props
property shallowly to enforce this. -
When you use JSX, you must start a tag with a capital letter to render your own custom component. In other words,
<Something />
is equivalent tocreateElement(Something)
, but<something />
(lowercase) is equivalent tocreateElement('something')
(note it’s a string, so it will be treated as a built-in HTML tag). -
You should only pass children as multiple arguments to
createElement
if they are all statically known, likecreateElement('h1', {}, child1, child2, child3)
. If your children are dynamic, pass the entire array as the third argument:createElement('ul', {}, listItems)
. This ensures that React will warn you about missingkey
s for any dynamic lists. For static lists this is not necessary because they never reorder.
Usage
Creating an element without JSX
If you don’t like JSX or can’t use it in your project, you can use createElement
as an alternative.
To create an element without JSX, call createElement
with some type, props, and children:
import { createElement } from 'react';
function Greeting({ name }) {
return createElement(
'h1',
{ className: 'greeting' },
'Hello ',
createElement('i', null, name),
'. Welcome!'
);
}
The children are optional, and you can pass as many as you need (the example above has three children). This code will display a <h1>
header with a greeting. For comparison, here is the same example rewritten with JSX:
function Greeting({ name }) {
return (
<h1 className="greeting">
Hello <i>{name}</i>. Welcome!
</h1>
);
}
To render your own React component, pass a function like Greeting
as the type instead of a string like 'h1'
:
export default function App() {
return createElement(Greeting, { name: 'Taylor' });
}
With JSX, it would look like this:
export default function App() {
return <Greeting name="Taylor" />;
}
Here is a complete example written with createElement
:
import { createElement } from 'react'; function Greeting({ name }) { return createElement( 'h1', { className: 'greeting' }, 'Hello ', createElement('i', null, name), '. Welcome!' ); } export default function App() { return createElement( Greeting, { name: 'Taylor' } ); }
And here is the same example written using JSX:
function Greeting({ name }) { return ( <h1 className="greeting"> Hello <i>{name}</i>. Welcome! </h1> ); } export default function App() { return <Greeting name="Taylor" />; }
Both coding styles are fine, so you can use whichever one you prefer for your project. The main benefit of using JSX compared to createElement
is that it’s easy to see which closing tag corresponds to which opening tag.
Deep Dive
An element is a lightweight description of a piece of the user interface. For example, both <Greeting name="Taylor" />
and createElement(Greeting, { name: 'Taylor' })
produce an object like this:
// Slightly simplified
{
type: Greeting,
props: {
name: 'Taylor'
},
key: null,
ref: null,
}
Note that creating this object does not render the Greeting
component or create any DOM elements.
A React element is more like a description—an instruction for React to later render the Greeting
component. By returning this object from your App
component, you tell React what to do next.
Creating elements is extremely cheap so you don’t need to try to optimize or avoid it.