React
/Beginner
React Elements
Definition
A React Element is the smallest building block of React apps. It is a plain JavaScript object describing what you want to see on the screen.
Explain Like I'm New
Imagine an architect drawing a blueprint. The blueprint is not a real house; it is just a piece of paper describing the house. A React Element is like that blueprint. It describes what a button or a div should look like, and React uses that blueprint to build the actual physical DOM element in the browser.
Real World Example
When you write `<div className="box"></div>` in JSX, Babel compiles it down to `React.createElement("div", {className: "box"})`. This function returns a plain object: `{ type: "div", props: { className: "box" } }`. This object is the Element.
Common Use Cases
- •Representing DOM nodes in memory
- •Passing UI descriptions around as variables
- •Being the return value of all React Components
Interactive Example
import React from "react"; export default function ElementDemo() { // 1. Using JSX (What you normally write) const jsxElement = <div className="box">Hello JSX</div>; // 2. What it compiles to (The actual React Element) const rawElement = React.createElement( "div", { className: "box", style: { color: "blue" } }, "Hello raw React.createElement" ); return ( <div> {jsxElement} {rawElement} <p>Both variables hold plain JavaScript objects, not real DOM nodes!</p> </div> ); }
Interview Questions
basic
- What is the difference between a React Element and a React Component?
- Are React Elements mutable or immutable?
intermediate
- What does `React.createElement` return?
- What happens if you try to modify the props of an Element after it is created?
advanced
- How does React use Elements in the Virtual DOM?
- What is the `$$typeof` property on a React Element used for?
trick
- Can a React Element be a function?