⚛️ Topic 6: Handling Events in React ⚛️ Topic 7: Conditional Rendering in React

React apps are interactive – buttons, input fields, forms, toggles — all need to respond to user actions. For that, we use event handling in React.
This article explains how to handle events like onClick, onChange, etc., in simple language, with real-life examples and clean code – helpful for both college students and working professionals.
🔹 What is an Event?
An event is an action performed by the user — like:
Clicking a button 🖱️
Typing in a text box ⌨️
Submitting a form 📤
Hovering over an element 🖱️
Just like in HTML and JavaScript, React allows you to listen to these events and respond using functions.
✅ 1. Adding Event Listeners in React
In React, you handle events using camelCase event names and by passing a function to them.
📌 Syntax:
<button onClick={myFunction}>Click Me</button>
🔁 Compare with HTML:
<button onclick="myFunction()">Click Me</button> <!-- lowercase -->
🧪 Example: Button Click Event
import React from 'react';
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<div>
<button onClick={handleClick}>Click Me</button>
</div>
);
}
export default App;
✅ 2. Event Handling in React
React passes an event object to your function — just like JavaScript.
function handleClick(event) {
console.log(event); // synthetic event object
}
React uses something called Synthetic Events — a wrapper around browser's native events — so it works the same across all browsers.
🧪 Example: Input Change Event
import React, { useState } from 'react';
function App() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<input type="text" onChange={handleChange} />
<p>Your name is: {name}</p>
</div>
);
}
🧠
event.target.valuegives the current value of the input field.
✅ 3. Arrow Functions in Event Handlers
You can also use arrow functions directly in JSX if the logic is short:
<button onClick={() => alert("Clicked!")}>Click</button>
⚠️ But be careful:
If your function has multiple lines or heavy logic, define it outside to keep your code clean.
🧪 Example: With Parameters
function showMessage(name) {
alert("Hello " + name);
}
// in JSX
<button onClick={() => showMessage("Riya")}>Greet</button>
⚠️ You must use arrow functions when passing parameters, or it will execute immediately.
✅ Best Practices for Event Handling
| Good Practice | Why? |
| Use arrow functions for small logic | Easy and quick |
| Define functions separately for bigger logic | Better readability |
Use onChange, onClick, onSubmit, etc. with camelCase | React standard |
Use state (useState) to store event-based data | Makes UI dynamic |
🧠 Real-Life Use Cases of Event Handling
| Use Case | Event |
| Clicking “Add to Cart” | onClick |
| Typing in a search bar | onChange |
| Submitting login form | onSubmit |
| Hovering over product image | onMouseOver |
✅ Summary
React uses camelCase for event names
Events are handled using functions —
onClick={myFunction}Use
useStateto track event-related dataArrow functions help when you want to pass arguments or write short logic
React provides SyntheticEvent — a cross-browser wrapper around native events.
⚛️ Mini Project: Simple Feedback Form
🎯 Objective: Learn how to collect user input using
event.target.value, handle events, and update state.
🧱 What You’ll Build:
A small form with:
Name input field 🧑
Feedback textarea 📝
Submit button 📤
Real-time preview below the form ✅
💡 Concepts Covered:
useStateonChange(for input and textarea)onClick(for submit)event.target.valueConditional rendering
📁 File: App.js
import React, { useState } from 'react';
function App() {
const [name, setName] = useState("");
const [feedback, setFeedback] = useState("");
const [submitted, setSubmitted] = useState(false);
function handleNameChange(event) {
setName(event.target.value);
}
function handleFeedbackChange(event) {
setFeedback(event.target.value);
}
function handleSubmit() {
if (name && feedback) {
setSubmitted(true);
} else {
alert("Please fill all fields.");
}
}
return (
<div style={{ padding: "20px", maxWidth: "500px", margin: "auto", fontFamily: "sans-serif" }}>
<h2>📝 Feedback Form</h2>
<input
type="text"
placeholder="Enter your name"
value={name}
onChange={handleNameChange}
style={{ width: "100%", padding: "10px", marginBottom: "10px" }}
/>
<textarea
placeholder="Your feedback..."
value={feedback}
onChange={handleFeedbackChange}
rows="5"
style={{ width: "100%", padding: "10px", marginBottom: "10px" }}
></textarea>
<button onClick={handleSubmit} style={{ padding: "10px 20px" }}>Submit</button>
{submitted && (
<div style={{ marginTop: "20px", background: "#f5f5f5", padding: "15px", borderRadius: "8px" }}>
<h3>Thank You, {name}!</h3>
<p><strong>Your Feedback:</strong></p>
<p>{feedback}</p>
</div>
)}
</div>
);
}
export default App;
🔍 Explanation:
| Part | What’s Happening |
useState() | To store user inputs and submitted status |
event.target.value | Gets user’s current input from input/textarea |
onChange | Triggers when user types something |
onClick | Fires when submit button is clicked |
submitted && (...) | Conditionally shows thank you message |
✅ What Students Will Learn:
How to capture form inputs
How to work with state and events
How
event.target.valueupdates stateReal-world form submission flow
Would you like an assignment based on this (with questions or tasks to complete)??
If you want please write in comment section “YES” , so that can i give you assignment based on this topic .
QUERIES : What is “event.target.value” 🤔🤔??
Bilkul! me btati hu aapko, Let’s break down event.target.value in super simple words 👇
✅ event.target.value – What is it?
When you interact with an input field (like typing something), React automatically captures that event.
event: This is the event object that React provides when something happens (like clicking or typing).event.target: This means the element that triggered the event (e.g.,<input>).event.target.value: This gives you the current value inside that element (what user typed).
🔹 Example to Understand:
function handleChange(event) {
console.log(event.target.value);
}
Let’s say you type “Ankit” in a text input.
event.target→<input type="text" />event.target.value→"Ankit"
So, event.target.value returns whatever the user has typed right now.
🧪 Real Example with Input Field:
import React, { useState } from 'react';
function App() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value); // Store user input in state
}
return (
<div>
<input type="text" onChange={handleChange} />
<p>You typed: {name}</p>
</div>
);
}
✅ As you type, React captures the value using event.target.value and stores it in state using setName().
🧠 In Simple Hindi:
"Jab user input field me kuch likhta hai, to
event.target.valuese usne kya likha hai wo milta hai."
📌 You’ll Mostly Use event.target.value With:
| Element | Event Used | Purpose |
<input> | onChange | Get text typed by user |
<textarea> | onChange | Get large input data |
<select> | onChange | Get selected value |
⚛️ Topic 7: Conditional Rendering in React
In real-life apps, we don’t always want to show everything on the screen. Sometimes we show a message, or hide a component, or display different UI based on conditions.
This is called 👉 Conditional Rendering in React.
✅ What is Conditional Rendering?
"Showing or hiding things on the screen based on a condition."
Just like if-else in JavaScript — React allows us to decide what to display, based on logic.
🔹 Real-Life Examples:
| Condition | What to Render |
| User is logged in | Show dashboard |
| User is not logged in | Show login form |
| Cart is empty | Show “No items” message |
| Button clicked | Show thank-you message |
🔧 Methods of Conditional Rendering in React:
We'll learn 3 popular ways:
if / else
Ternary operator (
? :)Logical AND (
&&)
🧪 Example Setup: Show/Hide a Message
We'll use a useState to toggle a message using a button.
import React, { useState } from 'react';
function App() {
const [show, setShow] = useState(false);
function toggleMessage() {
setShow(!show); // true -> false, false -> true
}
return (
<div style={{ padding: "20px" }}>
<button onClick={toggleMessage}>
{show ? "Hide Message" : "Show Message"}
</button>
{/* Conditional Rendering Below */}
{show && <p>🎉 This is a secret message!</p>}
</div>
);
}
✅ 1. Using if / else
You can’t use if/else directly inside JSX. So, we write logic above return.
function App() {
const isLoggedIn = true;
let content;
if (isLoggedIn) {
content = <h2>Welcome back, user! 🎉</h2>;
} else {
content = <h2>Please log in 🔐</h2>;
}
return (
<div>
{content}
</div>
);
}
✅ 2. Using Ternary Operator
Ternary works inside JSX — great for short conditions.
function App() {
const isDarkMode = false;
return (
<div>
<p>{isDarkMode ? "Dark Mode ON 🌙" : "Light Mode ON ☀️"}</p>
</div>
);
}
📝 Syntax:
condition ? doIfTrue : doIfFalse
✅ 3. Using && (Logical AND)
If you want to show something only when a condition is true, use &&.
function App() {
const isAdmin = true;
return (
<div>
<h1>Welcome, User</h1>
{isAdmin && <button>Go to Admin Panel</button>}
</div>
);
}
🧠 Think of this like:
“If
isAdminis true, then show the button.”
🔍 Summary Table
| Method | When to Use |
if / else | Complex conditions or multiple outputs |
Ternary ? : | Simple one-line condition |
&& | Only if you need to show (or not show) something |
📦 Real-World Use Cases
| Use Case | Code Example |
| Show success message after form submit | {isSubmitted && <p>Thanks!</p>} |
| Toggle password visibility | {showPassword ? "Hide" : "Show"} |
| Dark mode theme | theme === "dark" ? darkStyle : lightStyle |
| If cart has no items | cart.length === 0 && <p>No items yet.</p> |
✅ Wrap-up
React gives us flexible ways to show/hide things
if/else, ternary? :, and&&are most commonChoose the method based on how complex or simple the condition is
Conditional rendering is key to building interactive, user-friendly apps
QUERIES : 🔥 Let's clear your doubt in simple language
❓ Can we use if, else if, or switch-case in React?
✅ Yes, you can! But not directly inside JSX (the return part).
React is just JavaScript — so you can use
if,else if,switch-case— outside JSX, meaning above thereturn.
🚫 You CANNOT do this inside return:
// ❌ Wrong! This will give an error
return (
if (isLoggedIn) {
<h2>Welcome</h2>
}
);
✅ Instead, you do this:
✔️ Using if / else above return:
function App() {
const isLoggedIn = true;
let message;
if (isLoggedIn) {
message = <h2>Welcome back!</h2>;
} else {
message = <h2>Please log in.</h2>;
}
return (
<div>
{message}
</div>
);
}
✔️ Using switch-case above return:
function App() {
const userType = "admin";
let content;
switch (userType) {
case "admin":
content = <p>Welcome, Admin 🛡️</p>;
break;
case "guest":
content = <p>Welcome, Guest 🙋</p>;
break;
default:
content = <p>Hello, User 👋</p>;
}
return (
<div>
{content}
</div>
);
}
🧠 Important Tip:
React’s return statement only understands expressions, not statements like if, for, while, switch, etc.
So use conditions before the return, or use expressions like:
condition ? true : falsecondition && trueComponent
✅ Final Answer:
Yes! You can use if/else if/else and switch-case in React — just use them outside JSX or before return().
❓ Why can’t we use if, else, switch inside return() in React?
🧠 Because...
👉 return() in React contains JSX, and JSX is actually not normal JS — it’s JavaScript XML.
JSX allows you to write HTML-like code inside JavaScript, and it gets compiled into pure JavaScript function calls behind the scenes.
✅ JSX only allows expressions, not statements.
| ❌ Not allowed in JSX | ✅ Allowed in JSX |
if, for, switch (statements) | Ternary ? :, logical &&, function calls (expressions) |
🔍 What's the difference?
| Term | Meaning |
| Statement | Instructions like if, for, while, switch — control flow |
| Expression | Returns a value — like 2 + 2, user ? "Hi" : "Bye" |
🧠 JSX needs something that returns a value — like a tag, a variable, or a function output.
🔧 Under the hood...
This:
return (
<h1>Hello</h1>
)
is compiled by React into something like:
React.createElement('h1', null, 'Hello');
So you can’t put a full if statement inside return, because:
return (
if (isLoggedIn) { // ❌ This is a JS statement, not a value
<h1>Welcome</h1>
}
)
…is not valid JavaScript expression, hence it breaks.
✅ So, What Can We Do?
Use:
Ternary (
? :)&&logical operatorOr write
if-elselogic above return(), store in a variable, and then render that variable.
📦 Summary:
JSX wants expressions, not statements
if,else,switchare statements → not allowed insidereturnUse them above return, and assign JSX to a variable
Or use expressions like
? :and&&inside return
😃 Real-life 2 mini projects : ⬇️⬇️😃
Here are 2 real-life mini projects based on Conditional Rendering in React, explained with:
🧠 Project concept
🔄 How it works (flow)
🧩 React topics covered
💻 Responsive, real-life structured code
📚 Line-by-line explanation
🧩 Project 1: Login System UI (With Role-based Rendering)
🔷 Project Overview:
A login screen with two buttons:
Login as User
Login as Admin
Based on which role logs in:
Show User Dashboard
Or show Admin Dashboard
Also include a Logout button to hide everything again.
🛠 React Topics Covered:
Conditional rendering (
if/else,&&, ternary)useStatehookJSX
Component structure
Basic Event Handling (
onClick)Responsive design with simple CSS
🧠 Flow:
App starts ➝ No one is logged in
User clicks "Login as User" or "Login as Admin"
Dashboard content is shown based on login
Logout button resets everything
💻 Code:
// App.js
import React, { useState } from 'react';
import './App.css';
function App() {
const [role, setRole] = useState("");
function loginAsUser() {
setRole("user");
}
function loginAsAdmin() {
setRole("admin");
}
function logout() {
setRole("");
}
return (
<div className="container">
{!role && (
<div className="login-box">
<h2>Login Portal</h2>
<button onClick={loginAsUser}>Login as User</button>
<button onClick={loginAsAdmin}>Login as Admin</button>
</div>
)}
{role === "user" && (
<div className="dashboard user">
<h2>Welcome, User! 👋</h2>
<p>This is your user dashboard.</p>
<button onClick={logout}>Logout</button>
</div>
)}
{role === "admin" && (
<div className="dashboard admin">
<h2>Hello Admin! 🛠️</h2>
<p>This is the admin dashboard with extra access.</p>
<button onClick={logout}>Logout</button>
</div>
)}
</div>
);
}
export default App;
/* App.css */
body {
margin: 0;
padding: 0;
font-family: 'Segoe UI', sans-serif;
background: #f2f2f2;
}
.container {
max-width: 600px;
margin: auto;
padding: 40px 20px;
text-align: center;
}
.login-box, .dashboard {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
button {
padding: 10px 20px;
margin: 10px;
border: none;
border-radius: 6px;
cursor: pointer;
}
.dashboard.user {
background-color: #e0f7fa;
}
.dashboard.admin {
background-color: #fff3e0;
}
@media screen and (max-width: 600px) {
button {
width: 100%;
margin: 10px 0;
}
}
🔍 Summary:
| Feature | What’s Happening |
| Role-based UI | if, &&, ternary |
| Button clicks | onClick with state update |
| Reusability | Separated logic clearly |
| Responsive | CSS + media queries |
🧩 Project 2: Theme Toggle App (Light/Dark Mode)
🔷 Project Overview:
User clicks a button to switch between:
Light Mode ☀️
Dark Mode 🌙
Text and background colors change accordingly.
🛠 React Topics Covered:
useStateevent handlingConditional rendering (
ternary)JSX styling
Responsive layout
💡 Flow:
App loads in Light Mode
User clicks "Toggle Theme"
Theme and UI color update based on the selected mode
💻 Code:
// App.js
import React, { useState } from 'react';
import './App.css';
function App() {
const [darkMode, setDarkMode] = useState(false);
function toggleTheme() {
setDarkMode(!darkMode);
}
const themeStyle = {
backgroundColor: darkMode ? "#1e1e1e" : "#fefefe",
color: darkMode ? "#ffffff" : "#000000",
minHeight: "100vh",
padding: "40px",
transition: "all 0.3s ease",
};
return (
<div style={themeStyle}>
<h1>{darkMode ? "Dark Mode 🌙" : "Light Mode ☀️"}</h1>
<p>This is a simple theme switcher app using React.</p>
<button onClick={toggleTheme}>
Switch to {darkMode ? "Light" : "Dark"} Mode
</button>
</div>
);
}
export default App;
/* App.css */
button {
padding: 12px 24px;
font-size: 16px;
margin-top: 20px;
background-color: #6200ea;
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
}
button:hover {
opacity: 0.9;
}
🔍 Summary:
| Feature | What’s Happening |
| Theme switch | useState + ternary |
| Dynamic styling | Style object based on state |
| Transitions | Smooth color changes |
| Responsive | Works great on all devices |
✅ Wrap-Up
These 2 mini projects:
Are realistic & practical
Follow a clean component structure
Help practice conditional rendering deeply
Can be extended later with auth, APIs, routing, etc.
If you want:
🔗 GitHub-ready structure
📝 Assignment based on these
💡 More project ideas using other React topics (like Props, State, Lists, Hooks)
Just say the word! in below comment section .
🔔 Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant React notes, tutorials, and project ideas —
📩 Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
🎥 Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. 🚀

