Dynamic Element Types
Learn about the flexibility of different element types and dynamic runtime creation from custom components.
We'll cover the following...
Element type
An element type, the first input argument to createElement
, can be a simple string representing an HTML tag, such as h1
and span
. However, it can also take other formats, such as a function:
const Child = () => <h1>Hello World</h1>const Title = () => {return <Child />}
Here's what the compiler sees of the preceding code:
const Child = () =>React.createElement("h1", null, "Hello World")const Title = () => React.createElement(Child, null)
Note the Child
in the preceding code—the function itself is sent to createElement
as the element type! This is how React allows you to create an element out of a custom component. Because of this, it means we can support a dynamic element type at runtime:
const Child1 = () => <h1>Hello</h1>const Child2 = () => <h1>World</h1>const Title = ({ flag }) => {const Child = flag ? Child1 : Child2return <Child />}
In the preceding code, instead of returning either <Child1 />
...