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!

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!

What is React JS? Why is it Efficient? (Beginner-Friendly Guide)

If you are starting frontend development, one of the most popular technologies you’ll hear about is React JS.

But many beginners ask:

πŸ€” What exactly is React?
πŸ€” Why do companies prefer React over other frameworks?

In this guide, you’ll learn:

  • What React JS is
  • How it works
  • Why it is efficient
  • Real-world examples

What is React JS?

React is a JavaScript library used to build user interfaces (UI), especially for web applications.

πŸ‘‰ It was developed by Meta (formerly Facebook).


Simple Definition

React is a library that helps you build fast, interactive, and reusable UI components.


Example of React Code

function App() {
return <h1>Hello, World!</h1>;
}

πŸ‘‰ This renders a heading on the screen.


How React Works

React uses a component-based architecture.


What are Components?

Components are small reusable pieces of UI.

Example:

  • Header
  • Footer
  • Button
  • Form

Example

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

πŸ‘‰ You can reuse this anywhere in your app.


Why is React Efficient?

This is the most important question πŸ‘‡


1. Virtual DOM (Main Reason)

React uses something called the Virtual DOM.


What is DOM?

DOM = Document Object Model
πŸ‘‰ Represents your webpage structure


Problem with Normal DOM

  • Slow updates
  • Entire UI re-renders

React Solution: Virtual DOM

React creates a lightweight copy of the DOM.

πŸ‘‰ When data changes:

  • React compares old vs new (diffing)
  • Updates only changed parts

Result:

βœ” Faster updates
βœ” Better performance


2. Reusable Components

Instead of writing code again and again:

<Button />
<Button />
<Button />

πŸ‘‰ One component β†’ multiple uses


3. Efficient Rendering

React updates only what is needed:

❌ Not entire page
βœ… Only changed components


4. One-Way Data Flow

React uses unidirectional data flow:

πŸ‘‰ Parent β†’ Child

Benefits:

  • Easy debugging
  • Predictable behavior

5. Declarative Approach

Instead of telling β€œhow to update UI”:

πŸ‘‰ You describe β€œwhat UI should look like”

Example:

const isLoggedIn = true;return isLoggedIn ? <Dashboard /> : <Login />;

6. Strong Ecosystem

React has:

  • Huge community
  • Many libraries
  • Easy integrations

Real-World Example

Imagine a shopping app:

πŸ‘‰ When you add an item:

  • Only cart updates
  • Not entire page

πŸ‘‰ This is React efficiency πŸš€


React vs Traditional Approach

FeatureTraditional JSReact
UpdatesFull pagePartial
Code reuseLowHigh
PerformanceSlowerFaster

Common Misconceptions


❌ React is a Framework

πŸ‘‰ It’s actually a library


❌ React is only for big apps

πŸ‘‰ You can use it for small apps too


When to Use React?

Use React when:

  • Building dynamic UI
  • Creating large applications
  • Need reusable components

Interview Tip

If asked:

β€œWhy is React efficient?”

πŸ‘‰ Answer:

β€œBecause it uses Virtual DOM, updates only required parts, and uses reusable components.”


Final Summary

  • React is a UI library
  • Uses components
  • Virtual DOM improves performance
  • Efficient rendering saves time

πŸ‘‰ That’s why React is widely used πŸš€

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

Showing Alert For Page Refresh , Closing tab or Window If Unsaved changes are there in the Form – ReactJS

If unsaved changes are there in the form, we will use the following code to show default alert message when user tries to reload or close the window or close the tab.