React Components & JSX
Functional & class components, JSX syntax, props, and rendering elements
Components
JSX
Props
Elements
1. Introduction: The Building Blocks of React
React is all about components . Think of components as custom HTML elements that you create to build your user interface.
Concept One-Line Definition
Component A reusable piece of UI that can have its own data and behavior.
Functional Component A component defined as a JavaScript function.
Class Component A component defined as an ES6 class.
JSX A syntax extension that lets you write HTML-like code inside JavaScript.
Element The smallest building block of a React app (a plain JavaScript object).
2. What are React Components?
A component is like a blueprint for a part of your screen. It takes inputs (called props ) and returns what should appear on the screen (written in JSX).
Analogy: A component is like a stamp. You design it once, then you can stamp it anywhere, anytime.
JSX // A component is like a stamp - design once, use many times
<Button /> // Stamp 1
<Button /> // Stamp 2
<Button /> // Stamp 3
There are two ways to write components in React:
Functional Components (modern, preferred)
Class Components (older, still found in legacy code)
3. Functional Components
3.1 Syntax and Structure
A functional component is simply a JavaScript function that:
Returns JSX (or null)
Can accept an optional props parameter
JSX // Basic syntax
function ComponentName() {
return <h1>Hello, World!</h1>;
}
// Arrow function syntax (also valid)
const ComponentName = () => {
return <h1>Hello, World!</h1>;
};
// Implicit return (for one-liners)
const ComponentName = () => <h1>Hello, World!</h1>;
Rules for component names:
Must start with a capital letter (Button, not button)
Use PascalCase (capitalize every word: MyAwesomeButton)
3.2 Props in Functional Components
Props (short for "properties") are read-only inputs passed to a component.
JSX // Passing props to a component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Using the component
function App() {
return (
<div>
<Greeting name="Alice" />
<Greeting name="Bob" />
</div>
);
}
Destructuring props (cleaner syntax):
JSX // Method 1: Destructure in parameters
function Greeting({ name, age }) {
return <h1>Hello, {name}! You are {age} years old.</h1>;
}
// Method 2: Destructure inside function
function Greeting(props) {
const { name, age } = props;
return <h1>Hello, {name}! You are {age} years old.</h1>;
}
3.3 Default Props and Prop Types
JSX // Default props (if no value is provided)
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}
// Or using defaultProps (older syntax)
Greeting.defaultProps = {
name: "Guest"
};
3.4 Complete Code Example
JSX // Functional Component with props, state, and events
import { useState } from 'react';
function Counter({ initialCount = 0 }) {
const [count, setCount] = useState(initialCount);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
const reset = () => setCount(initialCount);
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h1>Functional Component Counter</h1>
<h2>Count: {count}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
}
export default Counter;
4. Class Components
4.1 Syntax and Structure
A class component is an ES6 class that:
Extends React.Component
Contains a render() method that returns JSX
Can have state and lifecycle methods
JSX import React from 'react';
class ComponentName extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
4.2 Props in Class Components
Props are accessed using this.props:
JSX class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
4.3 State in Class Components
State is data that can change over time within a component.
JSX class Counter extends React.Component {
// Method 1: Initialize state in constructor
constructor(props) {
super(props); // Must call super(props) first
this.state = { count: 0 };
}
// Method 2: Class property syntax (simpler)
state = { count: 0 };
render() {
return <h1>Count: {this.state.count}</h1>;
}
}
Updating state: Always use setState(), never modify this.state directly.
JSX // Correct
this.setState({ count: this.state.count + 1 });
// Wrong - will not re-render!
this.state.count = this.state.count + 1;
setState is asynchronous:
JSX // Use callback to get updated value
this.setState({ count: this.state.count + 1 }, () => {
console.log(this.state.count); // New value
});
4.4 Lifecycle Methods
Phase Method When it runs
Mounting constructor()When component is first created
Mounting componentDidMount()After component is added to DOM (good for API calls)
Updating componentDidUpdate(prevProps, prevState)After props or state change
Unmounting componentWillUnmount()Just before component is removed (cleanup)
JSX class Timer extends React.Component {
state = { seconds: 0 };
intervalId = null;
componentDidMount() {
this.intervalId = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 1000);
}
componentDidUpdate(prevProps, prevState) {
console.log(`Seconds changed from ${prevState.seconds} to ${this.state.seconds}`);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
return <h1>Timer: {this.state.seconds} seconds</h1>;
}
}
4.5 Complete Code Example
JSX import React from 'react';
class Counter extends React.Component {
state = { count: this.props.initialCount || 0 };
increment = () => this.setState({ count: this.state.count + 1 });
decrement = () => this.setState({ count: this.state.count - 1 });
reset = () => this.setState({ count: this.props.initialCount || 0 });
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log(`Count changed to ${this.state.count}`);
}
}
render() {
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h1>Class Component Counter</h1>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.reset}>Reset</button>
</div>
);
}
}
export default Counter;
5. Functional vs Class Components: Detailed Comparison
Feature Functional Component Class Component
Syntax A JavaScript function An ES6 class extending React.Component
Props Access props.name (parameter)this.props.name
State useState hookthis.state and this.setState()
Lifecycle useEffect hookcomponentDidMount, componentDidUpdate, etc.
this binding Not needed Required for event handlers
Code Length Shorter, cleaner Longer, more boilerplate
Current Status ✅ Preferred / Modern ⚠️ Legacy
Hooks Support Full support Cannot use hooks
Why Functional Components are Now Preferred
Hooks (React 16.8+) gave functional components state, lifecycle, and context.
Less boilerplate – No constructor, no this, no render() method.
Easier to test and debug.
React team recommends them for all new code.
JSX // Functional component (5 lines, same functionality)
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
6. What is JSX?
JSX (JavaScript XML) is a syntax extension that lets you write HTML-like code inside JavaScript.
JSX // Without JSX (plain JavaScript)
const element = React.createElement('h1', { className: 'greeting' }, 'Hello!');
// With JSX (much cleaner!)
const element = <h1 className="greeting">Hello!</h1>;
6.1 Why JSX?
Benefit Explanation
Familiar syntax Looks like HTML, easy to learn
Prevents injection attacks JSX escapes embedded values automatically
Readable See the UI structure at a glance
Compile-time errors Better error messages than raw createElement
6.2 JSX Syntax Rules
Rule Wrong Correct
One parent element <h1>A</h1><h2>B</h2><div><h1>A</h1><h2>B</h2></div>
Fragments Extra wrapper div <> <h1>A</h1> </>
Self-close empty tags <img><img />
className class="box"className="box"
htmlFor for="name"htmlFor="name"
Expressions in {} — id={"user-" + id}
6.3 Embedding JavaScript Expressions in JSX
JSX const name = "Alice";
const isLoggedIn = true;
const element = (
<div>
<p>Hello, {name}!</p>
<p>{isLoggedIn ? "Welcome back!" : "Please log in"}</p>
<p>{name.toUpperCase()}</p>
{/* You CANNOT use if/else directly — use ternary or && */}
</div>
);
6.4 JSX Attributes
JSX <img src="https://example.com/photo.jpg" />
<img src={imageUrl} />
<input disabled={true} />
<input disabled={false} />
6.5 JSX Children
JSX <div>Hello World</div>
<Container><Child /></Container>
<div>{getChildContent()}</div>
6.6 Conditional Rendering in JSX
JSX // Ternary operator
{isLoggedIn ? `Welcome back, ${username}!` : "Please sign in."}
// && operator
{isLoggedIn && <p>You have 3 new messages</p>}
6.7 Lists and Keys in JSX
JSX {todoList.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
Key rules: Must be unique among siblings; should be stable; use IDs from data when available.
6.8 JSX Behind the Scenes (Transpilation)
Babel converts JSX into React.createElement() calls:
JavaScript // JSX
const element = (
<div className="container">
<h1>Hello, {name}!</h1>
<button onClick={handleClick}>Click</button>
</div>
);
// What Babel produces (simplified)
const element = React.createElement(
'div',
{ className: 'container' },
React.createElement('h1', null, 'Hello, ', name, '!'),
React.createElement('button', { onClick: handleClick }, 'Click')
);
7. Rendering Elements in React
7.1 What is an Element?
A React element is the smallest building block — a plain JavaScript object describing what you want on screen.
Concept Description Analogy
React Element Plain object describing the DOM A blueprint
Component Function or class that returns elements A factory
DOM Element Actual browser HTML node The built house
7.2 Rendering an Element to the DOM
HTML <!-- index.html -->
<div id="root"></div>
JSX // React 18+ (modern)
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<h1>Hello, World!</h1>);
// React 17 and older (legacy)
import ReactDOM from 'react-dom';
ReactDOM.render(<h1>Hello, World!</h1>, document.getElementById('root'));
7.3 Updating Rendered Elements
React elements are immutable . To update the UI, create a new element and pass it to root.render():
JSX function tick() {
const element = (
<div>
<h1>Current Time:</h1>
<h2>{new Date().toLocaleTimeString()}</h2>
</div>
);
root.render(element);
}
setInterval(tick, 1000);
7.4 React Only Updates What's Necessary
React DOM compares the element and its children with the previous version (Virtual DOM diffing) and applies only the minimal changes to the real DOM — e.g., only the <h2> text updates each second.
8. Complete Working Example: Combining All Concepts
Full React app demonstrating functional components, class components, JSX, and rendering:
JSX — App.jsx import { useState } from 'react';
import React from 'react';
function WelcomeMessage({ name, isLoggedIn }) {
return (
<div className="welcome">
{isLoggedIn ? (
<h1>Welcome back, {name}!</h1>
) : (
<h1>Please sign in to continue</h1>
)}
</div>
);
}
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: "Learn React", completed: false },
{ id: 2, text: "Build a project", completed: false }
]);
const [inputValue, setInputValue] = useState("");
const addTodo = () => {
if (inputValue.trim()) {
setTodos([...todos, { id: Date.now(), text: inputValue, completed: false }]);
setInputValue("");
}
};
const toggleTodo = (id) => {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
));
};
return (
<div>
<h2>My Todo List</h2>
<input value={inputValue} onChange={(e) => setInputValue(e.target.value)} />
<button onClick={addTodo}>Add</button>
<ul>
{todos.map(todo => (
<li key={todo.id} onClick={() => toggleTodo(todo.id)}>{todo.text}</li>
))}
</ul>
</div>
);
}
class Clock extends React.Component {
state = { time: new Date() };
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: new Date() }), 1000);
}
componentWillUnmount() { clearInterval(this.interval); }
render() {
return (
<div>
<h3>Current Time</h3>
<p>{this.state.time.toLocaleTimeString()}</p>
</div>
);
}
}
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h1>React Components Demo</h1>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Logout' : 'Login'}
</button>
<WelcomeMessage name="Alice" isLoggedIn={isLoggedIn} />
<hr />
<TodoList />
<hr />
<Clock />
</div>
);
}
export default App;
9. Summary Cheat Sheet
JSX // FUNCTIONAL COMPONENT (PREFERRED)
function MyComponent({ name }) {
const [count, setCount] = useState(0);
useEffect(() => { return () => {}; }, [count]);
return <div>Hello, {name}! Count: {count}</div>;
}
// CLASS COMPONENT (LEGACY)
class MyComponent extends React.Component {
state = { count: 0 };
componentDidMount() { }
render() { return <div>Count: {this.state.count}</div>; }
}
// JSX RULES: one parent, {expressions}, className, self-close, keys
{isLoggedIn ? <Logout /> : <Login />}
{items.map(item => <li key={item.id}>{item.name}</li>)}
// RENDERING
import { createRoot } from 'react-dom/client';
createRoot(document.getElementById('root')).render(<App />);
Quick Decision Guide
You want to... Use this
Create a new component ✅ Functional Component + Hooks
Maintain internal data useState hook
Run code on mount/unmount useEffect hook
Pass data to child Props
Display a list JSX map() + key
Conditionally show/hide Ternary ? : or &&
Understand legacy code Class Component knowledge
Next Steps
Props vs State – When to use each
Event Handling – onClick, onChange, onSubmit
Forms in React – Controlled vs uncontrolled components
useEffect Deep Dive – Dependencies, cleanup, and common patterns
Context API – Sharing data without prop drilling
React Router – Navigation between pages
React Components & JSX MCQ Practice
10 Basic MCQs
10 Advanced MCQs
10 Basic React Components & JSX MCQs
1
A React component is best described as:
A A reusable piece of UI
B A database table
C A CSS file only
D An npm script
Explanation: Components encapsulate UI logic and markup.
2
JSX stands for:
A JavaScript XML syntax extension
B Java Standard Extension
C JSON XML
D Joint Style eXport
Explanation: JSX lets you write HTML-like syntax in JavaScript.
3
Which returns valid JSX?
A return <h1>Hello</h1>;
B return h1 Hello;
C return <h1> without closing
D return (Hello);
Explanation: JSX elements must be properly closed and wrapped.
4
A functional component is:
A A JavaScript function that returns JSX
B A class in CSS
C A Node.js module only
D A router path
Explanation: Modern React favors function components with hooks.
5
To render a component <App /> you use:
A ReactDOM createRoot render
B document.write only
C alert()
D npm start only
Explanation: createRoot(...).render(<App />) mounts the tree.
6
JSX attribute className replaces HTML:
A class
B id
C style only
D href
Explanation: class is reserved in JavaScript—use className.
7
Embedding JavaScript in JSX uses:
A Curly braces {}
B Square brackets only
C Angle brackets only
D Semicolons only
Explanation: Example: {user.name}.
8
A component name must start with:
A Uppercase letter
B Lowercase only
C Number
D Underscore only
Explanation: Capitalized names distinguish components from HTML tags.
9
Fragment shorthand syntax is:
A <> ... </>
B <fragment> only in HTML
C <div required>
D <!-- -->
Explanation: Fragments group children without extra DOM nodes.
10
Self-closing JSX tags look like:
A <img />
B <img> only without slash
C <img closed>
D <IMG></img> required always
Explanation: Void elements in JSX must be self-closed.
10 Advanced React Components & JSX MCQs
1
JSX compiles to:
A React.createElement calls
B Raw HTML strings only
C SQL queries
D CSS modules only
Explanation: Babel/transform tools convert JSX to createElement.
2
Why must JSX have one parent element (or Fragment)?
A createElement returns a single root node
B Browsers forbid multiple nodes
C JSX cannot use fragments
D React has no Virtual DOM
Explanation: Multiple siblings need a wrapper or Fragment.
3
Spreading props in JSX: <Avatar {...user} /> means:
A Pass all properties of user as props
B Delete user object
C Import CSS
D Enable strict mode
Explanation: Spread passes each key as a separate prop.
4
dangerouslySetInnerHTML should be used:
A Only with sanitized HTML to avoid XSS
B For all user text by default
C Instead of JSX always
D To replace useState
Explanation: Never pass unsanitized user HTML.
5
Pure component concept means:
A Same props/state yield same output
B No JavaScript allowed
C Cannot use hooks
D Must be a class only
Explanation: Purity helps reasoning and optimization.
6
Default export vs named export for components:
A Both work; be consistent with import style
B Only default is valid in React
C Named exports break JSX
D Exports are not used
Explanation: export default function App() vs export function Button().
7
Children prop lets you:
A Nest content inside a component
B Replace React DOM
C Skip re-renders always
D Access npm
Explanation: <Card>{content}</Card> passes children.
8
React 18 createRoot enables:
A Concurrent features and batching improvements
B Removing Virtual DOM
C Using class components only
D Disabling hydration
Explanation: createRoot is the React 18+ entry API.
9
Component composition prefers:
A Many small components over one giant file
B One 10,000-line component
C Inline styles only
D Global variables
Explanation: Compose UI from focused reusable pieces.
10
JSX expression {items.length} renders:
A A number in the DOM
B Nothing ever
C An error always
D A React component class
Explanation: Primitives like numbers and strings render as text nodes.
Check All Answers
15 React Components & JSX Interview Questions & Answers
Easy
Medium
Hard
1 What is a React component?easy
Answer: A reusable function or class that accepts props and returns JSX describing UI.
2 What is JSX?easy
Answer: A syntax extension allowing HTML-like markup inside JavaScript, compiled to React elements.
3 Why use className instead of class?easy
Answer: Because class is a reserved keyword in JavaScript.
4 Difference between element and component?medium
Answer: An element is a plain object describing DOM/node; a component is a function/class that may return elements.
5 What is React.createElement?medium
Answer: The runtime function JSX compiles into, creating React element objects.
6 When to use React.Fragment?medium
Answer: When you need multiple siblings without adding an extra wrapper div to the DOM.
7 Can a component return null?medium
Answer: Yes—returning null renders nothing, useful for conditional UI.
8 What are props in JSX?easy
Answer: Inputs passed to components, read-only from the child's perspective.
9 How do you comment inside JSX?medium
Answer: Wrap comments in {/* comment */} inside the JSX tree.
10 What is the children prop?medium
Answer: Special prop containing nested JSX passed between opening and closing tags.
11 Functional vs class components today?medium
Answer: Functional components with hooks are standard; classes are legacy for new code.
12 What is component composition?hard
Answer: Building complex UIs by nesting smaller components instead of inheritance.
13 Why capitalize component names?easy
Answer: So React treats them as components rather than intrinsic HTML tags.
14 What happens if JSX is not transpiled?hard
Answer: Browsers cannot parse JSX—they need Babel/Vite/esbuild transformation.
15 Explain mounting in React.hard
Answer: The first time React renders a component tree into a DOM container via createRoot().render().