Dynamic Element Types
Explore how React handles dynamic element types determined at runtime using the createElement function. Understand what React elements are, including their internal types like react.element, react.memo, and react.provider. This lesson helps you comprehend the structure and flexibility of React elements and why different types exist for various cases in application updates.
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 /> or <Child2 />, we ...