Skip to main content

🌱 React Basics – A Beginner Friendly Guide (With Examples)

you’re new to React, this post will walk you through all the fundamentals you need to get started.

We’ll cover:
✔ What React is
✔ Components
✔ JSX
✔ Props & State
✔ Event Handling
✔ Conditional Rendering
✔ Lists & Keys
✔ A small demo Todo App

By the end, you’ll have a solid foundation to start building apps in React 🚀.


1. ⚛️ What is React?

Definition
React is a JavaScript library for building user interfaces.
It was developed by Facebook (Meta) and is widely used to build dynamic, fast, and interactive web applications.

Explanation

  • Traditional web apps: You manually update the DOM.
  • React apps: React uses a virtual DOM → it calculates the minimal changes needed and updates the real DOM efficiently.

Key Features

  • Component-based → Build UI as small reusable blocks
  • Declarative → You describe what the UI should look like
  • One-way data flow → Data flows from parent → child via props

Minimal React Starter (using CDN)

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>React 18 Starter</title>
  </head>
  <body>
    <div id="root"></div>

    <!-- React 18 + ReactDOM 18 -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <!-- Babel for JSX (dev only) -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <script type="text/babel">
      const { createRoot } = ReactDOM;
      function App() {
        return <h1>Hello React 👋</h1>;
      }
      const root = createRoot(document.getElementById('root'));
      root.render(<App />);
    </script>
  </body>
</html>

2. 🧩 Components

Definition
A component is a reusable piece of UI (button, card, navbar).
Components return JSX and can accept props + manage their own state.

Functional Component (modern way)

function Hello({ name }) {
  return <h2>Hello, {name}!</h2>;
}

// Usage
<Hello name="Tushar" />

Class Component (older way)

class HelloClass extends React.Component {
  render() {
    return <h2>Hello, {this.props.name}!</h2>;
  }
}

// Usage
<HelloClass name="Tushar" />

👉 Use functional components with hooks in modern React.


3. ✨ JSX Syntax

Definition
JSX (JavaScript XML) looks like HTML but lives inside JavaScript.

Explanation

  • JSX makes UI code declarative & readable.
  • Under the hood → compiled to plain JavaScript.

Important Rules

  • Use className instead of class.
  • Event names → camelCase (onClick, onChange).
  • Wrap multiple elements in <div> or <>...</>.

Example

function Card() {
  const title = "JSX Tips";
  return (
    <div className="card">
      <h3>{title}</h3>
      <p style={{ marginTop: 8 }}>Inline styles are objects.</p>
      <>
        <small>This is inside a fragment.</small>
      </>
    </div>
  );
}

4. 📦 Props and State

🔹 Props

Definition → Inputs from parent → child (read-only).
Example

function UserBadge({ username, role = "Reader" }) {
  return <span>@{username} — {role}</span>;
}

// Usage
<UserBadge username="tushar" role="Admin" />
<UserBadge username="guest" /> {/* defaults to Reader */}

🔹 State

Definition → Data that changes over time inside a component.
Managed withuseState hook.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <h3>Count: {count}</h3>
      <button onClick={() => setCount(count - 1)}>-</button>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

👉 Props = inputs | State = internal data.


5. 🖱 Event Handling

Definition
Event handling lets you capture user actions (clicks, typing, form submits).

Explanation

  • Events use camelCase.
  • You pass a function, not a string.

Example

import { useState } from "react";

function SignupForm() {
  const [email, setEmail] = useState("");

  function handleSubmit(e) {
    e.preventDefault();
    alert("Signed up: " + email);
    setEmail("");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="you@example.com"
      />
      <button type="submit">Sign Up</button>
    </form>
  );
}

6. 🔀 Conditional Rendering

Definition
Conditionally show UI based on state/props.

Examples

// Using if
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) return <p>Welcome back!</p>;
  return <p>Please sign in.</p>;
}

// Using &&
function Discount({ percent }) {
  return <div>{percent >= 10 && <p>🎉 You have a discount!</p>}</div>;
}

// Using ternary
function Status({ online }) {
  return <span>Status: {online ? "🟢 Online" : "⚪️ Offline"}</span>;
}

7. 📋 Lists and Keys

Definition
Render lists with .map(). Each element needs a unique key.

const products = [
  { id: "p1", name: "Keyboard" },
  { id: "p2", name: "Mouse" },
  { id: "p3", name: "Monitor" },
];

function ProductList() {
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>{p.name}</li> // ✅ stable unique key
      ))}
    </ul>
  );
}

👉 Never use array indexes as keys (unless static).


8. 📝 Small Demo App – Todo App

Let’s combine everything: props, state, events, lists, conditional rendering.

import { useState } from "react";

function TodoItem({ todo, onToggle }) {
  return (
    <li>
      <label>
        <input
          type="checkbox"
          checked={todo.done}
          onChange={() => onToggle(todo.id)}
        />
        <span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
          {todo.text}
        </span>
      </label>
    </li>
  );
}

function TodoApp() {
  const [text, setText] = useState("");
  const [todos, setTodos] = useState([
    { id: "t1", text: "Learn React", done: false },
    { id: "t2", text: "Build something", done: true },
  ]);

  function addTodo(e) {
    e.preventDefault();
    if (!text.trim()) return;
    setTodos((list) => [
      { id: crypto.randomUUID(), text, done: false },
      ...list,
    ]);
    setText("");
  }

  function toggleTodo(id) {
    setTodos((list) =>
      list.map((t) => (t.id === id ? { ...t, done: !t.done } : t))
    );
  }

  const remaining = todos.filter((t) => !t.done).length;

  return (
    <div>
      <h2>Todos ({remaining} left)</h2>

      <form onSubmit={addTodo}>
        <input
          value={text}
          onChange={(e) => setText(e.target.value)}
          placeholder="Add a todo..."
        />
        <button type="submit">Add</button>
      </form>

      {todos.length === 0 ? (
        <p>No todos yet. Add one!</p>
      ) : (
        <ul>
          {todos.map((t) => (
            <TodoItem key={t.id} todo={t} onToggle={toggleTodo} />
          ))}
        </ul>
      )}
    </div>
  );
}

🔑 Recap

  • React is a UI library that makes building apps easier and faster.
  • Components → Reusable building blocks.
  • JSX → Write HTML-like syntax in JS.
  • Props → Pass data into components.
  • State → Store dynamic data inside a component.
  • Events → Handle user interactions.
  • Conditional Rendering → Show UI based on conditions.
  • Lists & Keys → Efficiently render multiple items.

Comments

Popular posts from this blog

🌟 Dot net Microservices interview questions

Here is a comprehensive list of 200 .NET microservices coding questions covering all core microservices concepts and cross-cutting concerns relevant for designing, building, deploying, and maintaining .NET-based distributed systems. 🧩 A. Microservices Fundamentals (20) Build a microservice in .NET 8 that exposes a simple CRUD API. Implement communication between two microservices using REST. How would you design microservices for an e-commerce application? Create a microservice that handles user registration and login. How do you isolate domain logic in a microservice? How to apply the "Single Responsibility Principle" in microservices? Design a service registry/discovery mechanism using custom middleware. Implement a service that handles file uploads and metadata separately. Build a stateless microservice and explain its benefits. Implement health check endpoints in .NET 8. Demonstrate versioning in a microservice API. Add Swagger/OpenAPI support to your m...

⚡ Part 1: Introduction to Generics in C#

🌍 Why Do We Need Generics? Imagine you want to create a stack (like a pile of books 📚): You can push items on top You can pop items off the top If we write a stack for integers : public class IntStack { private int[] items = new int[10]; private int index = 0; public void Push(int item) => items[index++] = item; public int Pop() => items[--index]; } 👉 Problem: This only works for int . What if we want a string stack ? Or a Customer stack ? We’d have to duplicate code for every type. 😢 ✅ Solution: Generics Generics let us create type-safe reusable code without duplication. We can say: “I don’t care what type it is yet — I’ll decide later.” 1) Generic Classes Here’s a generic stack : // Generic class "Stack<T>" // The <T> is a placeholder for any type public class Stack<T> { private T[] items = new T[10]; // Array of type T private int index = 0; // Push adds an item of type T public void P...

🚪 Part 9: API Gateway for .NET 8 Microservices (Ocelot & YARP)

Once you have multiple microservices (Products, Orders, Payments…), exposing each one directly to clients gets messy: Different base URLs Duplicated auth logic No unified rate limiting / caching Hard to evolve routes or aggregate data 👉 Enter the API Gateway — your single front door for all microservices. An API Gateway handles: ✅ Routing & path rewriting ✅ Load balancing, retries, circuit breakers ✅ Authentication & Authorization (JWT, OAuth2) ✅ Rate limiting & caching ✅ Aggregation (compose results from multiple services) In this post we’ll implement two strong options: Ocelot → config-driven, mature, DevOps-friendly YARP (Yet Another Reverse Proxy) → Microsoft’s code-first, extensible gateway ⚖️ Ocelot vs YARP — When to Choose Ocelot → JSON config, minimal C#, built-in QoS (rate limit, circuit breaker). Perfect for teams that like DevOps config-as-code. YARP → full C# control, middleware-friendly, can embed into broader apps (e.g. add dashb...