React Components & JSX

Functional & class components, JSX syntax, props, and rendering elements

Components JSX Props Elements

Table of Contents

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.

ConceptOne-Line Definition
ComponentA reusable piece of UI that can have its own data and behavior.
Functional ComponentA component defined as a JavaScript function.
Class ComponentA component defined as an ES6 class.
JSXA syntax extension that lets you write HTML-like code inside JavaScript.
ElementThe 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
JSXimport 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:

JSXclass 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.

JSXclass 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

PhaseMethodWhen it runs
Mountingconstructor()When component is first created
MountingcomponentDidMount()After component is added to DOM (good for API calls)
UpdatingcomponentDidUpdate(prevProps, prevState)After props or state change
UnmountingcomponentWillUnmount()Just before component is removed (cleanup)
JSXclass 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

JSXimport 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

FeatureFunctional ComponentClass Component
SyntaxA JavaScript functionAn ES6 class extending React.Component
Props Accessprops.name (parameter)this.props.name
StateuseState hookthis.state and this.setState()
LifecycleuseEffect hookcomponentDidMount, componentDidUpdate, etc.
this bindingNot neededRequired for event handlers
Code LengthShorter, cleanerLonger, more boilerplate
Current Status✅ Preferred / Modern⚠️ Legacy
Hooks SupportFull supportCannot 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?

BenefitExplanation
Familiar syntaxLooks like HTML, easy to learn
Prevents injection attacksJSX escapes embedded values automatically
ReadableSee the UI structure at a glance
Compile-time errorsBetter error messages than raw createElement

6.2 JSX Syntax Rules

RuleWrongCorrect
One parent element<h1>A</h1><h2>B</h2><div><h1>A</h1><h2>B</h2></div>
FragmentsExtra wrapper div<> <h1>A</h1> </>
Self-close empty tags<img><img />
classNameclass="box"className="box"
htmlForfor="name"htmlFor="name"
Expressions in {}id={"user-" + id}

6.3 Embedding JavaScript Expressions in JSX

JSXconst 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.

ConceptDescriptionAnalogy
React ElementPlain object describing the DOMA blueprint
ComponentFunction or class that returns elementsA factory
DOM ElementActual browser HTML nodeThe 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():

JSXfunction 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.jsximport { 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 datauseState hook
Run code on mount/unmountuseEffect hook
Pass data to childProps
Display a listJSX map() + key
Conditionally show/hideTernary ? : or &&
Understand legacy codeClass 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:

AA reusable piece of UI
BA database table
CA CSS file only
DAn npm script
Explanation: Components encapsulate UI logic and markup.
2

JSX stands for:

AJavaScript XML syntax extension
BJava Standard Extension
CJSON XML
DJoint Style eXport
Explanation: JSX lets you write HTML-like syntax in JavaScript.
3

Which returns valid JSX?

Areturn <h1>Hello</h1>;
Breturn h1 Hello;
Creturn <h1> without closing
Dreturn (Hello);
Explanation: JSX elements must be properly closed and wrapped.
4

A functional component is:

AA JavaScript function that returns JSX
BA class in CSS
CA Node.js module only
DA router path
Explanation: Modern React favors function components with hooks.
5

To render a component <App /> you use:

AReactDOM createRoot render
Bdocument.write only
Calert()
Dnpm start only
Explanation: createRoot(...).render(<App />) mounts the tree.
6

JSX attribute className replaces HTML:

Aclass
Bid
Cstyle only
Dhref
Explanation: class is reserved in JavaScript—use className.
7

Embedding JavaScript in JSX uses:

ACurly braces {}
BSquare brackets only
CAngle brackets only
DSemicolons only
Explanation: Example: {user.name}.
8

A component name must start with:

AUppercase letter
BLowercase only
CNumber
DUnderscore 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:

AReact.createElement calls
BRaw HTML strings only
CSQL queries
DCSS modules only
Explanation: Babel/transform tools convert JSX to createElement.
2

Why must JSX have one parent element (or Fragment)?

AcreateElement returns a single root node
BBrowsers forbid multiple nodes
CJSX cannot use fragments
DReact has no Virtual DOM
Explanation: Multiple siblings need a wrapper or Fragment.
3

Spreading props in JSX: <Avatar {...user} /> means:

APass all properties of user as props
BDelete user object
CImport CSS
DEnable strict mode
Explanation: Spread passes each key as a separate prop.
4

dangerouslySetInnerHTML should be used:

AOnly with sanitized HTML to avoid XSS
BFor all user text by default
CInstead of JSX always
DTo replace useState
Explanation: Never pass unsanitized user HTML.
5

Pure component concept means:

ASame props/state yield same output
BNo JavaScript allowed
CCannot use hooks
DMust be a class only
Explanation: Purity helps reasoning and optimization.
6

Default export vs named export for components:

ABoth work; be consistent with import style
BOnly default is valid in React
CNamed exports break JSX
DExports are not used
Explanation: export default function App() vs export function Button().
7

Children prop lets you:

ANest content inside a component
BReplace React DOM
CSkip re-renders always
DAccess npm
Explanation: <Card>{content}</Card> passes children.
8

React 18 createRoot enables:

AConcurrent features and batching improvements
BRemoving Virtual DOM
CUsing class components only
DDisabling hydration
Explanation: createRoot is the React 18+ entry API.
9

Component composition prefers:

AMany small components over one giant file
BOne 10,000-line component
CInline styles only
DGlobal variables
Explanation: Compose UI from focused reusable pieces.
10

JSX expression {items.length} renders:

AA number in the DOM
BNothing ever
CAn error always
DA React component class
Explanation: Primitives like numbers and strings render as text nodes.

15 React Components & JSX Interview Questions & Answers

Easy Medium Hard
1What is a React component?easy
Answer: A reusable function or class that accepts props and returns JSX describing UI.
2What is JSX?easy
Answer: A syntax extension allowing HTML-like markup inside JavaScript, compiled to React elements.
3Why use className instead of class?easy
Answer: Because class is a reserved keyword in JavaScript.
4Difference 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.
5What is React.createElement?medium
Answer: The runtime function JSX compiles into, creating React element objects.
6When to use React.Fragment?medium
Answer: When you need multiple siblings without adding an extra wrapper div to the DOM.
7Can a component return null?medium
Answer: Yes—returning null renders nothing, useful for conditional UI.
8What are props in JSX?easy
Answer: Inputs passed to components, read-only from the child's perspective.
9How do you comment inside JSX?medium
Answer: Wrap comments in {/* comment */} inside the JSX tree.
10What is the children prop?medium
Answer: Special prop containing nested JSX passed between opening and closing tags.
11Functional vs class components today?medium
Answer: Functional components with hooks are standard; classes are legacy for new code.
12What is component composition?hard
Answer: Building complex UIs by nesting smaller components instead of inheritance.
13Why capitalize component names?easy
Answer: So React treats them as components rather than intrinsic HTML tags.
14What happens if JSX is not transpiled?hard
Answer: Browsers cannot parse JSX—they need Babel/Vite/esbuild transformation.
15Explain mounting in React.hard
Answer: The first time React renders a component tree into a DOM container via createRoot().render().