Ads

Ad

React Basics: JSX and Functional Components with JyotiOfCode

 

Introduction

If you’ve successfully installed React and set up Tailwind CSS, congratulations — you’ve taken the first step into the world of modern front-end development!
But what comes next?
In this article, we’ll walk you through a complete React learning roadmap, step-by-step — from basics to advanced concepts — so you can become a confident React developer.




Introduction to JSX and Functional Components in React (with Tailwind CSS)

When you're just starting with React, two things form the backbone of your learning:

  • JSX – a syntax that looks like HTML, but behaves like JavaScript.

  • Functional Components – small, reusable UI pieces written as JavaScript functions.

In this article, we’ll explain what JSX and functional components are, how to use them, and provide simple examples you can run and understand.


What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that lets you write HTML-like code inside your JavaScript files. JSX makes it easier to visualize and write UI in React.

Example:

jsx
const element = <h1 className="text-2xl font-bold text-blue-500">Hello, React!</h1>;

Instead of doing:

js
const element = React.createElement("h1", {}, "Hello, React!");

Key JSX Rules to Remember:

  1. Return only ONE parent element

jsx
return ( <div> <h1>Hello</h1> <p>World</p> </div> ); // ✅ Correct // ❌ Wrong (multiple root elements) // return ( // <h1>Hello</h1> // <p>World</p> // );
  1. Use className instead of class (because class is a reserved JS keyword)

jsx
<p className="text-red-500">React with Tailwind!</p>

  1. Wrap dynamic values inside {}

jsx
const name = "Aditya"; return <h1>Hello, {name}</h1>;

Works with:

  • variables

  • expressions: {score > 50 ? "Pass" : "Fail"}

  • function calls: {getGreeting()}

  • array mapping: {items.map(item => <li>{item}</li>)}

  • conditions: {isLoggedIn && <p>Welcome back</p>}

4.Use camelCase for attributes

JSX uses camelCase for HTML attributes.

HTML AttributeJSX Equivalent
onclickonClick
tabindextabIndex
maxlengthmaxLength
jsx
<button onClick={handleClick}>Click Me</button>

5. Self-close empty tags

If a tag doesn’t have children, it must be self-closed.

jsx
// ✅ Correct: <img src="logo.png" alt="Logo" /> <input type="text" /> // ❌ Incorrect: <img src="logo.png"></img>

6.Avoid putting statements inside JSX

You can use expressions but not full statements like if, for, etc.

jsx
// ✅ Use ternary: {isDark ? <DarkMode /> : <LightMode />} // ❌ Invalid: { if (isDark) { return <DarkMode /> } }

7. Add key to list items

Whenever you render a list with .map(), each item must have a unique key.

jsx
{fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))}

key helps React identify which items changed, added, or removed.

8. No inline styles as strings

You must pass inline styles as an object, with camelCase keys:

jsx
// ✅ Correct: <div style={{ color: 'red', fontSize: '20px' }}>Styled Text</div> // ❌ Incorrect: <div style="color: red;">Invalid</div>

9.JavaScript inside JSX must be valid

Only expressions (not full statements) are allowed inside {}:

jsx
// ✅ Expressions: <h1>{2 + 2}</h1> // ❌ This will throw an error: <h1>{let x = 5}</h1>

What are Functional Components?

A Functional Component in React is just a plain JavaScript function that:

  • starts with a capital letter

  • returns JSX

  • can accept props as arguments

These are the modern way to create components — replacing older class-based components.

Basic Syntax

jsx
function Welcome() { return <h1>Welcome to my app!</h1>; }

Or using arrow function (commonly preferred):

jsx
const Welcome = () => { return <h1>Welcome to my app!</h1>; }

Usage:

jsx
<Welcome />

Why Functional Components Are Better:

FeatureDescription
 ReusableYou can reuse the same component with different props
 Simple SyntaxShorter and cleaner than class components
 Hooks SupportYou can use useState, useEffect, etc. inside functional components
 Better PerformanceSlightly more optimized than class-based components
 Easy to TestEasier to write unit tests for pure functions

Passing Props to Functional Components

Props = input parameters to the component

jsx
const Greet = (props) => { return <h2>Hello, {props.name}</h2>; }; <Greet name="Aditya" />

Using Destructuring:

jsx
const Greet = ({ name }) => { return <h2>Hello, {name}</h2>; };

Using useState in Functional Components

useState lets you add state to functional components.

jsx
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div className="p-4"> <p className="text-xl">Count: {count}</p> <button className="bg-blue-500 text-white px-4 py-2 rounded" onClick={() => setCount(count + 1)}> Increment </button> </div> ); };

Using useEffect in Functional Components

useEffect lets you run side effects (API calls, event listeners, etc.)

jsx
import React, { useEffect, useState } from 'react'; const GitHubUser = () => { const [user, setUser] = useState(null); useEffect(() => { fetch('https://api.github.com/users/adityajyoti') .then(res => res.json()) .then(data => setUser(data)); }, []); return ( <div> {user ? <h2>{user.name}</h2> : <p>Loading...</p>} </div> ); };

Reusability Example

jsx
const UserCard = ({ name, email }) => { return ( <div className="p-4 border rounded shadow"> <h2 className="font-bold">{name}</h2> <p>{email}</p> </div> ); }; // Usage <UserCard name="Aditya Jyoti" email="aditya@example.com" /> <UserCard name="Rahul Sharma" email="rahul@example.com" />

Recommended Folder Structure

css
/src /components Header.jsx Footer.jsx UserCard.jsx App.jsx index.js

Functional vs Class Components (Comparison)

FeatureFunctional ComponentClass Component
SyntaxFunctionES6 Class
StateuseStatethis.state
LifecycleuseEffectcomponentDidMount(), etc.
Code LengthShorter & cleanerMore boilerplate
PerformanceSlightly betterSlightly slower
Modern Practice Yes Legacy

Previously Covered Topics:

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!