React SVG Import: What Does “ReactComponent as” Mean?

If you’ve worked with React, you might have seen this syntax:

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

And wondered:

πŸ€” What is ReactComponent?
πŸ€” How is an SVG becoming a React component?
πŸ€” When should we use this?

Let’s break it down step-by-step in a very simple way πŸ‘‡


What Does This Syntax Mean?

import { ReactComponent as SomeIcon } from 'assets/some-icon.svg';

πŸ‘‰ This means:

β€œImport the SVG file and use it as a React component”


Usage

<SomeIcon />

πŸ‘‰ Instead of:

<img src="some-icon.svg" />

How Does This Actually Work?

This is not plain JavaScript behavior.

πŸ‘‰ It is handled by your build tool (like Webpack or Vite).


Behind the Scenes

Tools like:

  • SVGR (SVG to React transformer)

convert your SVG file into:

function SomeIcon(props) {
return (
<svg {...props}>
{/* SVG content */}
</svg>
);
}

πŸ‘‰ So your SVG becomes a React component internally


Normal SVG vs React Component

❌ Traditional Way

<img src="/icon.svg" alt="icon" />

βœ… React Component Way

import { ReactComponent as Icon } from './icon.svg';

<Icon />

Why Use SVG as React Component?


1. Easy Styling

<Icon style={{ color: 'red', width: 50 }} />

πŸ‘‰ You can style it like a component


2. Dynamic Props

<Icon width={30} height={30} />

3. Better Control

You can:

  • Change color
  • Animate
  • Add events

Add Event Handlers

<Icon onClick={() => alert('Clicked')} />

Example (Real Usage)

SVG File

<!-- icon.svg -->
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>

React Usage

import { ReactComponent as Icon } from './icon.svg';

function App() {
return <Icon width={40} height={40} />;
}

Styling with CSS

.icon {
fill: blue;
}
<Icon className="icon" />

Important Note (Color Control)

For dynamic color:

πŸ‘‰ SVG must use:

fill="currentColor"

πŸ‘‰ Then:

<Icon style={{ color: 'green' }} />

Common Mistakes

❌ Using wrong import

import Icon from './icon.svg'; // ❌

πŸ‘‰ This gives image path, not component


❌ Missing configuration

πŸ‘‰ Works only if:

  • CRA (Create React App)
  • Vite (with plugin)
  • Webpack configured

When It Works Automatically

Works out-of-the-box in:

  • Create React App
  • Vite (with SVGR plugin)
  • Next.js (with config)

When to Use <img> vs Component

Use <img> when:

  • Simple display
  • No styling needed

Use React Component when:

  • Need styling
  • Need animations
  • Need dynamic behavior

Interview Tip

If asked:

β€œWhat is ReactComponent as in SVG import?”

πŸ‘‰ Answer:

β€œIt converts SVG into a React component using tools like SVGR, allowing us to use it like JSX.”


Final Summary

  • ReactComponent converts SVG β†’ React component
  • Enables styling, events, and dynamic behavior
  • Powered by tools like SVGR
  • Better than <img> for interactive UI

Related Articles


πŸ’‘ Found this helpful? Subscribe for simple React tips, real-world examples, and developer-friendly tutorials. Happy Coding!

Higher Order Components (HOC) in React: Complete Guide with Examples

When working with React, you’ll often need to reuse logic across multiple components.

That’s where Higher Order Components (HOC) come into the picture.

In this guide, you’ll learn:

  • What a Higher Order Component is
  • Why we need it
  • How it works
  • Multiple real-world examples
  • When to use and when to avoid

What is a Higher Order Component (HOC)?

Simple Definition

A Higher Order Component (HOC) is a function that takes a component and returns a new enhanced component.


Syntax

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Simple Example

function withLogger(Component) {
return function EnhancedComponent(props) {
console.log("Component rendered");
return <Component {...props} />;
};
}

πŸ‘‰ Usage:

function Button() {
return <button>Click</button>;
}

const EnhancedButton = withLogger(Button);

Why Do We Need HOC?

Without HOC:

❌ Duplicate logic in multiple components

With HOC:

βœ… Reuse logic
βœ… Cleaner code
βœ… Better maintainability


How HOC Works (Step-by-Step)

  1. Take a component as input
  2. Add extra logic
  3. Return a new component
  4. Render original component with props

Scenario 1: Logging (Basic Example)

function withLogger(Component) {
return function (props) {
console.log("Props:", props);
return <Component {...props} />;
};
}

Scenario 2: Authentication (Very Common)

HOC

function withAuth(Component) {
return function (props) {

const { isLoggedIn } = useContext(AuthContext);

if (!isLoggedIn) {
return <h2>Please Login</h2>;
}

return <Component {...props} />;
};
}

Usage

function Dashboard() {
return <h1>Welcome to Dashboard</h1>;
}

export default withAuth(Dashboard);

Scenario 3: API Data Fetching


HOC

import { useEffect, useState } from "react";

function withData(Component, url) {
return function (props) {
const [data, setData] = useState([]);

useEffect(() => {
fetch(url)
.then(res => res.json())
.then(setData);
}, []);

return <Component data={data} {...props} />;

};
}

Usage

function Users({ data }) {
return <div>{data.length} Users</div>;
}

export default withData(Users, "/api/users");

Scenario 4: Loading State

function withLoading(Component) {
return function ({ isLoading, ...props }) {
if (isLoading) return <p>Loading...</p>;
return <Component {...props} />;
};
}

Scenario 5: Reusing Styles

function withStyle(Component) {
return function (props) {
return (
<div style={{ border: "1px solid black", padding: "10px" }}>
<Component {...props} />
</div>
);
};
}

Common Mistakes


❌ Forgetting to pass props

return <Component />; // ❌

πŸ‘‰ Fix:

return <Component {...props} />; // βœ…

❌ Mutating original component

πŸ‘‰ Always return a new component


HOC vs Hooks


HOC

  • Works with class components
  • Reusable logic

Hooks

  • Simpler
  • Preferred in modern React

When to Use HOC

Use HOC when:

  • You need reusable logic
  • Working with legacy/class components
  • Cross-cutting concerns (auth, logging)

When to Avoid HOC

Avoid when:

  • Hooks can solve it easily
  • Too many nested HOCs (complexity increases)

🧠 Interview Tip

If asked:

β€œWhat is HOC?”

πŸ‘‰ Answer:

β€œA Higher Order Component is a function that takes a component and returns a new component with added functionality.”


🏁 Final Summary

  • HOC = function that enhances components
  • Helps reuse logic
  • Used for auth, logging, data fetching
  • Hooks are modern alternative

πŸ”— Related Articles

πŸ‘‰ Add these:


πŸ’‘ Found this helpful? Subscribe for simple React guides, real-world examples, and interview preparation tips. Happy Coding!

Type vs Interface in TypeScript: Complete Guide with Examples (Beginner to Advanced)

When working with TypeScript, one of the most common questions is:

πŸ€” Should I use type or interface?

Both are used to define the structure of data, but they behave differently in certain scenarios.

In this guide, you’ll learn:

  • What type and interface are
  • Key differences
  • All important scenarios with examples
  • When to use each (very important)

What is interface in TypeScript?

An interface is used to define the structure (shape) of an object.


Basic Example

interface User {
name: string;
age: number;
}
const user: User = {
name: "Raju",
age: 25,
};

What is type in TypeScript?

A type is more flexible and can define:

  • Objects
  • Primitives
  • Unions
  • Tuples
  • Functions

Basic Example

type User = {
name: string;
age: number;
};

πŸ‘‰ Works similar to interface for objects


Key Differences (Quick Overview)

Featureinterfacetype
Object structureβœ… Yesβœ… Yes
Union types❌ Noβœ… Yes
Intersection types⚠️ Limitedβœ… Yes
Declaration mergingβœ… Yes❌ No
FlexibilityMediumHigh

Scenario 1: Object Definition

πŸ‘‰ Both work the same

interface User {
name: string;
}
type User = {
name: string;
};

βœ… No major difference here


Scenario 2: Declaration Merging (Important)

βœ… interface supports merging

interface User {
name: string;
}

interface User {
age: number;
}

πŸ‘‰ Result:

{
name: string;
age: number;
}

❌ type does NOT support merging

type User = {
name: string;
};

type User = {
age: number;
}; // ❌ Error

Scenario 3: Union Types

βœ… Using type

type Status = "success" | "error" | "loading";

❌ interface cannot do this

πŸ‘‰ Not supported


Scenario 4: Intersection Types

βœ… Using type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

⚠️ interface alternative

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

Scenario 5: Functions

βœ… Using type

type Add = (a: number, b: number) => number;

βœ… Using interface

interface Add {
(a: number, b: number): number;
}

Scenario 6: Extending / Inheritance

interface

interface Person {
name: string;
}

interface Employee extends Person {
salary: number;
}

type

type Person = {
name: string;
};

type Employee = Person & {
salary: number;
};

Scenario 7: Primitive Types

βœ… Only type supports this

type ID = string | number;

πŸ‘‰ interface cannot do this ❌


Scenario 8: Tuples

type Point = [number, number];

πŸ‘‰ Only type supports tuples


Scenario 9: Working with Classes

interface (preferred)

interface User {
name: string;
}

class Person implements User {
name = "Raju";
}

When to Use interface

Use interface when:

  • Defining object structure
  • Working with classes
  • Need declaration merging
  • Building large applications

When to Use type

Use type when:

  • Using unions (|)
  • Using intersections (&)
  • Working with primitives
  • Advanced type logic

Best Practice (Very Important)

πŸ‘‰ Use both together:

type Status = "success" | "error";

interface ApiResponse {
status: Status;
data: string;
}

Common Mistakes


❌ Using interface for unions

interface Status = "success" | "error"; // ❌

❌ Overusing any

πŸ‘‰ Avoid losing type safety


❌ Confusion between both

πŸ‘‰ Use based on use case


Interview Tip

If asked:

β€œtype vs interface?”

πŸ‘‰ Answer:

β€œBoth define data shapes, but type is more flexible (supports unions, tuples), while interface supports declaration merging and is better for object-oriented design.”


Final Summary

  • Both define structure of data
  • interface β†’ best for objects & classes
  • type β†’ best for advanced types
  • Use both based on need

πŸ’‘ Found this helpful? Subscribe to get simple TypeScript tutorials, interview questions, and real-world coding tips. Happy Coding!

TypeScript Error: β€œObject literal may only specify known properties” (Fix Explained)

While working with TypeScript, you might encounter this error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

This error can be confusing for beginners.

In this guide, you’ll learn:

  • What this error means
  • Why it happens
  • How to fix it (step-by-step)
  • Common mistakes to avoid

What Does This Error Mean?

πŸ‘‰ In simple terms:

TypeScript is telling you that you are adding a property that is not defined in the type or interface


Example That Causes the Error

interface User {
name: string;
}

const user: User = {
name: "Raju",
age: 25, // ❌ Error here
};

πŸ‘‰ Error:

Object literal may only specify known properties, and 'age' does not exist in type 'User'

Why This Error Happens

TypeScript uses strict type checking.

πŸ‘‰ It ensures that:

  • You only use properties defined in the type
  • No extra or unexpected data is added

How to Fix This Error


Fix 1: Add the Missing Property

If the property is valid, add it to the interface:

interface User {
name: string;
age: number;
}

πŸ‘‰ Now it works βœ…


Fix 2: Remove Extra Property

If the property is not needed:

const user: User = {
name: "Raju",
};

Fix 3: Use Index Signature (Flexible Objects)

If object can have dynamic properties:

interface User {
name: string;
[key: string]: any;
}

πŸ‘‰ Allows extra properties βœ…


Fix 4: Use Type Assertion (Use Carefully)

const user = {
name: "Raju",
age: 25,
} as User;

⚠️ This tells TypeScript to ignore extra properties
πŸ‘‰ Use only when you are sure


Fix 5: Assign Object to Variable First

const temp = {
name: "Raju",
age: 25,
};

const user: User = temp;

πŸ‘‰ This may bypass strict checking in some cases


⚠️ Common Mistakes


❌ Typo in property name

namee: "Raju" // ❌ wrong

❌ Forgetting to update interface

πŸ‘‰ Adding new fields but not updating type


❌ Overusing any

πŸ‘‰ Removes TypeScript benefits


Real-World Scenario

Imagine:

πŸ‘‰ API returns:

{
"name": "Raju",
"age": 25
}

But your interface is:

interface User {
name: string;
}

πŸ‘‰ You’ll get this error


Best Practices

  • Keep types updated
  • Avoid unnecessary properties
  • Use strict typing
  • Avoid overusing any

Interview Tip

If asked:

β€œWhat is this error?”

πŸ‘‰ Answer:

β€œIt occurs when an object contains properties that are not defined in its type or interface.”


Final Summary

  • TypeScript enforces strict object structure
  • Extra properties cause this error
  • Fix by updating type or removing extra fields
  • Use index signature for flexible objects

Related Articles


πŸ’‘ Facing more TypeScript errors? Subscribe to get simple fixes, real-world examples, and developer-friendly explanations. Happy Coding!

What is DOM, Virtual DOM, and Real DOM in React? (Simple Explanation for Beginners)

If you are new to web development or React, you might have heard terms like:

  • DOM
  • Virtual DOM
  • Real DOM

And it can feel confusing πŸ˜…

Don’t worry β€” in this guide, we’ll explain everything in very simple terms, even if you are not from a technical background.


What is DOM?

DOM stands for:

Document Object Model

πŸ‘‰ In simple words:

DOM is a structure of your web page


Real-Life Analogy

Think of a web page like a house 🏠

  • Walls β†’ HTML elements
  • Furniture β†’ Content
  • Layout β†’ Structure

πŸ‘‰ DOM is like the blueprint of the house


Example

<h1>Hello</h1>
<p>Welcome to my website</p>

πŸ‘‰ Browser converts this into a structure like:

Page
β”œβ”€β”€ h1 β†’ "Hello"
└── p β†’ "Welcome to my website"

What is Real DOM?

Real DOM is:

The actual DOM in the browser


Problem with Real DOM

Whenever something changes:

πŸ‘‰ The browser may rebuild or update large parts of the page

This can be:

  • Slow
  • Inefficient
  • Costly for performance

Example

Imagine:

πŸ‘‰ You change one word on the page

❌ Browser may re-check or update entire section


What is Virtual DOM?

Virtual DOM is a concept used by React


Simple Definition

Virtual DOM is a lightweight copy of the Real DOM


Real-Life Analogy

Think like this:

πŸ‘‰ Instead of directly editing your house 🏠
πŸ‘‰ You first make changes in a model (mini version)

Then:

βœ” Compare changes
βœ” Update only what is needed


How Virtual DOM Works (Step-by-Step)


Step 1: Initial Render

React creates:
πŸ‘‰ Virtual DOM
πŸ‘‰ Real DOM


Step 2: State Changes

When something changes:

πŸ‘‰ React creates a new Virtual DOM


Step 3: Comparison (Diffing)

React compares:

  • Old Virtual DOM
  • New Virtual DOM

Step 4: Update Only Changes

πŸ‘‰ React updates only the changed parts in Real DOM


Example (Very Simple)


Initial UI

<h1>Hello</h1>

Updated UI

<h1>Hello World</h1>

What React Does

❌ Does NOT reload whole page
βœ… Updates only text inside <h1>


Why Virtual DOM is Faster

FeatureReal DOMVirtual DOM
UpdatesFull or largeOnly required parts
SpeedSlowerFaster
EfficiencyLowHigh

Key Differences (Simple Table)

FeatureReal DOMVirtual DOM
TypeActual UICopy of UI
SpeedSlowFast
UpdatesDirectIndirect
Used byBrowserReact

Why React Uses Virtual DOM

React uses Virtual DOM to:

βœ” Improve performance
βœ” Reduce unnecessary updates
βœ” Make apps faster


Real-World Example

Imagine a shopping app:

πŸ‘‰ You add 1 item

❌ Without Virtual DOM β†’ entire page refresh
βœ… With Virtual DOM β†’ only cart updates


Common Misunderstanding


❌ Virtual DOM replaces Real DOM

πŸ‘‰ Not true

πŸ‘‰ It works along with Real DOM


Interview Tip

If asked:

β€œWhat is Virtual DOM?”

πŸ‘‰ Answer:

β€œIt is a lightweight copy of the Real DOM used by React to efficiently update only changed parts of the UI.”


Final Summary

  • DOM = structure of webpage
  • Real DOM = actual browser DOM
  • Virtual DOM = lightweight copy used by React
  • React updates only changed parts β†’ faster performance

πŸ’‘ Found this helpful? Subscribe to get simple explanations of complex concepts, React tutorials, and coding tips. Happy Coding!