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!

AI Can Make Mistakes: Why Developers Must Always Verify Before Trusting

Artificial Intelligence is transforming the way we write code, debug issues, and build products.

From generating functions to explaining complex concepts, AI tools feel like a superpower.

But here’s the truth that every developer must understand:

⚠️ AI can make mistakes. And sometimes, very confidently.


What Does It Mean That AI Can Make Mistakes?

AI doesn’t β€œknow” things the way humans do.

It doesn’t:

  • Understand truth
  • Verify facts in real-time
  • Guarantee correctness

Instead, it works based on patterns learned from data.

πŸ‘‰ This leads to something called:

AI Hallucination

AI hallucination means generating information that sounds correct but is actually wrong or misleading.


Example of AI Mistake

Imagine asking AI:

πŸ‘‰ β€œWrite a function to sort numbers”

It may give you code that:

  • Works for some cases βœ…
  • Fails for edge cases ❌
  • Uses outdated methods ⚠️

πŸ‘‰ If you blindly copy-paste β†’ bugs enter your system


The Real Responsibility Lies with Developers

This is the most important part:

πŸ’‘ AI is your assistant. You are the decision maker.

Think of it like this:

  • AI = Junior helper
  • Developer = Boss

πŸ‘‰ The assistant suggests
πŸ‘‰ The boss decides


Why You Should Never Blindly Trust AI

❌ 1. AI Can Be Confidently Wrong

AI often gives answers that look perfectβ€”but are incorrect.


❌ 2. No Context Awareness

AI may not fully understand:

  • Your project structure
  • Business logic
  • Edge cases

❌ 3. Outdated Information

Sometimes AI suggestions:

  • Use deprecated APIs
  • Ignore latest best practices

❌ 4. Security Risks

Blindly trusting AI can lead to:

  • Vulnerable code
  • Poor authentication logic
  • Unsafe API usage

What a Good Developer Should Do

1. Always Cross-Check

  • Read the code carefully
  • Verify logic
  • Test different scenarios

2. Test Everything

Never skip testing:

  • Edge cases
  • Error handling
  • Performance

3. Verify with Documentation

Always confirm with:

  • Official docs
  • Trusted sources

4. Use Your Logic

Ask yourself:

  • Does this make sense?
  • Is this optimal?
  • Is there a better way?

5. Think About Security

Before using AI-generated code:

  • Validate inputs
  • Avoid exposing sensitive data
  • Follow best practices

Real-World Analogy

Imagine:

You are a team lead, and AI is a junior developer.

πŸ‘‰ The junior writes code
πŸ‘‰ You review it

Would you deploy it without checking?

πŸ‘‰ No.

Same rule applies here.


What Happens If You Trust AI Blindly?

  • Bugs in production
  • Security vulnerabilities
  • Poor performance
  • Loss of user trust

Smart Way to Use AI

Use AI as:

βœ… Idea generator
βœ… Code helper
βœ… Learning assistant

But not as:

❌ Final decision maker
❌ Source of truth


Developer Mindset (Very Important)

β€œDon’t copy-paste. Understand and verify.”

This mindset separates:

πŸ‘‰ Average developers
πŸ‘‰ From great developers


🏁 Final Thoughts

AI is powerful. No doubt.

But:

πŸ’‘ A powerful tool in careless hands can create problems.

As a developer:

  • You are responsible
  • You make the final call
  • You own the product

πŸ‘‰ So don’t go blind.

πŸ‘‰ Think, verify, and then implement.


πŸ’‘ If this content is helpful to you, please subscribe. More practical developer insights are coming. 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!

Avoid Direct Node Access in Testing Library: Error Explained with Fixes & Examples

While writing tests using React Testing Library, you may see this warning:

Avoid direct Node access. Prefer using the methods from Testing Library

This can be confusing, especially for beginners

In this guide, you’ll learn:

  • What this warning means
  • Why it happens
  • How to fix it (step-by-step)
  • Best practices with examples

What Does This Error Mean?

πŸ‘‰ In simple terms:

You are accessing DOM elements directly (like document.querySelector) instead of using Testing Library methods.


❌ Example That Causes This Warning

const element = document.querySelector('.btn');
expect(element.textContent).toBe('Submit');

πŸ‘‰ Problem:

  • Direct DOM access
  • Not user-focused ❌

Why This is a Problem?

Testing Library follows this principle:

βœ… β€œTest the app the way users use it”

Users don’t use:

  • querySelector
  • getElementById

πŸ‘‰ They interact with:

  • Text
  • Buttons
  • Labels

Correct Way Using Testing Library

Example Fix

import { render, screen } from '@testinglibrary/react';

render(<button>Submit</button>);
const button = screen.getByText('Submit');
expect(button).toBeInTheDocument();

πŸ‘‰ Now:

  • Uses Testing Library methods βœ…
  • Matches real user behavior βœ…

Common Scenarios & Fixes

❌ Scenario 1: Using querySelector

const el = container.querySelector('.title');

βœ… Fix

screen.getByText('Title');

❌ Scenario 2: Using getElementById

document.getElementById('username');

βœ… Fix

screen.getByLabelText('Username');

❌ Scenario 3: Accessing container directly

const { container } = render(<App />);
const el = container.firstChild;

βœ… Fix

screen.getByRole('heading');

Best Queries to Use

Testing Library provides powerful queries:


By Role (Best)

screen.getByRole('button');

By Text

screen.getByText('Submit');

By Label

screen.getByLabelText('Email');

By Placeholder

screen.getByPlaceholderText('Enter name');

Query Priority (Very Important)

Follow this order:

  1. getByRole
  2. getByLabelText
  3. getByText
  4. getByPlaceholderText
  5. getByTestId (last option)

When is Direct DOM Access Allowed?

πŸ‘‰ Rare cases only:

  • Debugging
  • Complex DOM structure
  • No accessible selectors available

Example:

const { container } = render(<App />);
console.log(container.innerHTML);

Real-World Example

❌ Bad Test

const { container } = render(<button>Login</button>);
expect(container.firstChild.textContent).toBe('Login');

βœ… Good Test

render(<button>Login</button>);
expect(screen.getByText('Login')).toBeInTheDocument();

Why Testing Library Recommends This

  • Better readability
  • More maintainable tests
  • Closer to real user behavior
  • Encourages accessibility

Common Mistakes


❌ Overusing getByTestId

πŸ‘‰ Use only when necessary


❌ Ignoring accessibility

πŸ‘‰ Use roles and labels


❌ Writing implementation-based tests

πŸ‘‰ Focus on user behavior


Interview Tip

If asked:

β€œWhy avoid direct DOM access?”

πŸ‘‰ Answer:

β€œBecause Testing Library encourages testing from the user’s perspective using accessible queries instead of implementation details.”


Final Summary

  • Avoid direct DOM methods (querySelector, getElementById)
  • Use Testing Library queries (getByRole, getByText)
  • Write user-focused tests
  • Follow query priority

πŸ’‘ Writing tests? Subscribe to get simple testing guides, real-world examples, and debugging tips. Happy Coding!

Prompt Engineering vs RAG vs Fine-Tuning: Differences Explained with Examples

With the rise of AI tools like ChatGPT, many developers and beginners are hearing terms like:

  • Prompt Engineering
  • RAG (Retrieval-Augmented Generation)
  • Fine-tuning

But what do they actually mean? πŸ€”

In this guide, you’ll learn:

  • What each concept is
  • How they work
  • Key differences
  • Real-world examples
  • When to use each

1. What is Prompt Engineering?

Simple Definition

Prompt Engineering is the process of writing better inputs (prompts) to get better outputs from AI.


Example

❌ Bad Prompt

Explain React

πŸ‘‰ Output: Basic explanation


βœ… Good Prompt

Explain React in simple terms with real-world examples for beginners

πŸ‘‰ Output: Clear, structured answer


Key Idea

πŸ‘‰ You are not changing the AI model
πŸ‘‰ You are only improving how you ask questions


When to Use

  • Chatbots
  • Content generation
  • Coding help
  • Quick improvements

2. What is RAG (Retrieval-Augmented Generation)?

Simple Definition

RAG combines AI with external data sources to give more accurate answers.


Real-Life Analogy

πŸ‘‰ Imagine:

  • AI = Student
  • Database = Book

πŸ‘‰ Instead of guessing, the student:

  • Looks into the book
  • Then answers

How It Works

  1. User asks a question
  2. System searches database/documents
  3. Relevant data is retrieved
  4. AI generates answer using that data

Example

Without RAG

What is my company policy?

πŸ‘‰ AI doesn’t know ❌


With RAG

πŸ‘‰ System fetches policy from database
πŸ‘‰ AI answers correctly βœ…


Use Cases

  • Chatbots with company data
  • Customer support systems
  • Knowledge base search

3. What is Fine-Tuning?

Simple Definition

Fine-tuning is training an AI model with your own data to make it specialized.


Real-Life Analogy

πŸ‘‰ AI = Fresh graduate
πŸ‘‰ Fine-tuning = Job training


Example

You train model with:

Customer support conversations

πŸ‘‰ Now AI:

  • Talks like your support team
  • Understands your domain

Use Cases

  • Domain-specific AI (medical, finance)
  • Brand-specific tone
  • Custom chatbots

Key Differences (Very Important)

FeaturePrompt EngineeringRAGFine-Tuning
Changes model?❌ No❌ Noβœ… Yes
Uses external data?❌ Noβœ… Yesβœ… Yes
CostLowMediumHigh
ComplexityEasyMediumAdvanced
SpeedFastMediumSlow setup
Best forQuick resultsDynamic dataDeep customization

Real-World Comparison Example

Scenario: Company Chatbot

πŸ”Ή Prompt Engineering

πŸ‘‰ Ask better questions
❌ No company data


πŸ”Ή RAG

πŸ‘‰ Fetch company documents
βœ… Always updated


πŸ”Ή Fine-Tuning

πŸ‘‰ Train model on company data
βœ… Deep understanding


When to Use What?

Use Prompt Engineering when:

  • You need quick improvements
  • No custom data required
  • Beginner level

Use RAG when:

  • You have external data
  • Data changes frequently
  • Need accurate answers

Use Fine-Tuning when:

  • You need custom behavior
  • Domain-specific AI
  • High accuracy required

Best Approach (Pro Tip)

πŸ‘‰ In real-world applications:

βœ… Combine all three:

  • Prompt Engineering β†’ better instructions
  • RAG β†’ real-time data
  • Fine-tuning β†’ deeper intelligence

Common Mistakes


❌ Thinking prompt engineering is enough

πŸ‘‰ Not for complex systems


❌ Using fine-tuning for dynamic data

πŸ‘‰ Use RAG instead


❌ Ignoring RAG

πŸ‘‰ Leads to outdated answers


Interview Tip

If asked:

β€œPrompt vs RAG vs Fine-tuning?”

πŸ‘‰ Answer:

β€œPrompt engineering improves input, RAG adds external knowledge, and fine-tuning customizes the model itself.”


Final Summary

  • Prompt Engineering β†’ Better questions
  • RAG β†’ External data integration
  • Fine-tuning β†’ Model training

πŸ‘‰ Each solves different problems


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