React — Elements
What are Elements?
Elements are the smallest building blocks of React apps. They describe what you want to see on the screen.
Creating Elements
// Creating an element
const element = <h1>Hello, world!</h1>;
// With attributes
const element = <div className="container">Content</div>;
// With children
const element = (
<div>
<h1>Title</h1>
<p>Paragraph</p>
</div>
);
Rendering Elements
// Rendering to DOM
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(element);
// Multiple elements
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
Virtual DOM
React uses a virtual DOM to optimize updates:
// React updates only what changed
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
Element Updates
// Elements are immutable
const element1 = <h1>Hello</h1>;
const element2 = <h1>World</h1>;
// You create new elements, don't modify existing ones
const element = <div>{element1} {element2}</div>;
DOM Elements vs React Elements
// DOM element
const div = document.createElement('div');
div.textContent = 'Hello';
// React element
const element = <div>Hello</div>;
// React elements are plain objects
console.log(element);
// { type: 'div', props: { children: 'Hello' } }
Mini Practice
Write React code that:
- Creates a basic element
- Renders an element to the DOM
- Creates nested elements
- Understands element immutability
Up Next
Next: Learn about React Components.
Related Topics
Frequently Asked Questions about Elements
What is Elements in React?
Elements is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Elements?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Elements.
Why is Elements important in React?
Elements is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.