React - A JavaScript Library for Building User Interfaces
React is an open-source JavaScript library developed by Facebook for building interactive user interfaces with a component-based architecture.
What is React?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called "components". React was first released in 2013 and has since become one of the most popular frontend libraries.
Key Features
Component-Based
Build encapsulated components that manage their own state, then compose them to make complex UIs.
Virtual DOM
React creates an in-memory cache of the DOM and only updates what changed, making rendering efficient.
Declarative
Describe what your UI should look like for each state rather than how to change it.
Why Use React?
Benefits of React
- Reusable Components: Build encapsulated components that manage their own state and compose them to make complex UIs.
- Performance: Virtual DOM makes updates efficient by only re-rendering what changed.
- Large Ecosystem: Rich set of libraries and tools (React Router, Redux, Next.js, etc.)
- Strong Community: Backed by Facebook and thousands of open-source contributors.
- Cross-Platform: React Native for mobile apps, React VR for virtual reality.
- Job Opportunities: One of the most in-demand skills for frontend developers.
- Progressive: Can be adopted incrementally and works well with other technologies.
Getting Started with React
Setting Up a React Project
The easiest way to start a new React project is by using Create React App (CRA), which sets up your development environment with everything you need:
# Using npm
npx create-react-app my-app
cd my-app
npm start
# Or using yarn
yarn create react-app my-app
cd my-app
yarn start
This creates a new React project with a development server running at http://localhost:3000
and enables hot-reloading (automatic refresh when you save changes).
Basic React File Structure
my-app/
├── node_modules/ # All third-party dependencies
├── public/ # Static files
│ ├── index.html # Main HTML file
│ └── favicon.ico
├── src/ # Your React source files
│ ├── App.css # Main CSS file
│ ├── App.js # Main React component
│ ├── index.css # Global styles
│ ├── index.js # Application entry point
│ └── logo.svg
├── package.json # Project configuration and scripts
└── README.md # Project documentation
Step-by-Step Guide to Creating a Basic React App
Building Your First React App
Follow these steps to create a simple React application with a counter component, perfect for BCA students starting with React. We'll use Create React App and Tailwind CSS for styling.
Step 1: Install Node.js
Node.js is required to run React projects. Download and install it from nodejs.org. Verify the installation:
node -v
npm -v
This should display the Node.js and npm versions (e.g., v20.x.x and v10.x.x).
Step 2: Create a New React App
Use Create React App to set up a new project named my-counter-app
:
npx create-react-app my-counter-app
cd my-counter-app
This creates a project folder with all necessary files and dependencies.
Step 3: Install Tailwind CSS
Add Tailwind CSS for styling. Install the required packages:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Update tailwind.config.js
to include your source files:
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Replace the contents of src/index.css
with Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 4: Create a Counter Component
Replace the contents of src/App.js
with a simple counter component:
import { useState } from 'react';
import './App.css';
function App() {
const [count, setCount] = useState(0);
return (
My First React Counter
Count: {count}
);
}
export default App;
This creates a counter with increment, decrement, and reset buttons, styled with Tailwind CSS.
Step 5: Clean Up Default Files
Remove unused files to keep your project clean. Delete src/App.css
, src/logo.svg
, and update src/App.js
to remove references to them.
Update src/index.js
to ensure it renders the App
component:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
);
Step 6: Run the Application
Start the development server:
npm start
Your app will open in the browser at http://localhost:3000
. You should see a counter with buttons to increment, decrement, and reset the count.
Step 7: Build for Production
When ready to deploy, create an optimized build:
npm run build
This generates a build/
folder with production-ready files. You can deploy these to a hosting service like Netlify or Vercel.
User Scenario: Priya's First React App
Priya, a BCA student, wants to build her first React app. She follows these steps:
- Priya downloads Node.js from nodejs.org and verifies it with
node -v
(outputs v20.11.0) andnpm -v
(outputs v10.2.4). - She opens her terminal and runs
npx create-react-app my-counter-app
, then navigates to the project withcd my-counter-app
. - Priya installs Tailwind CSS by running the commands above and configures
tailwind.config.js
andindex.css
. - She replaces
src/App.js
with the counter component code, deletes unnecessary files (App.css
,logo.svg
), and ensuresindex.js
is correct. - Priya runs
npm start
, openshttp://localhost:3000
in her browser, and sees her counter app. She clicks the buttons to test incrementing, decrementing, and resetting the count. - Excited, Priya builds her app for production with
npm run build
and plans to deploy it to Vercel for her portfolio.
By following these steps, Priya successfully builds and runs her first React app, gaining confidence in React development.
Core Concepts
Components
The building blocks of React applications. Components let you split the UI into independent, reusable pieces.
// Functional Component
function Welcome(props) {
return Hello, {props.name}
;
}
// Class Component
class Welcome extends React.Component {
render() {
return Hello, {this.props.name}
;
}
}
// Usage:
JSX
JavaScript XML - syntax extension that allows writing HTML-like code in JavaScript.
const element = Hello, world!
;
// Equivalent to:
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
// JSX expressions become regular JavaScript:
const name = 'John';
const element = Hello, {name}
;
State
Data that changes over time in a component. Managed with the useState Hook in functional components.
import { useState } from 'react';
function Counter() {
// Declare a state variable "count" with initial value 0
const [count, setCount] = useState(0);
return (
You clicked {count} times
);
}
Props
Short for "properties" - read-only data passed from parent to child components.
// Parent component
function App() {
return ;
}
// Child component
function Welcome(props) {
return (
Hello, {props.name}. You are {props.age} years old.
);
}
// With destructuring
function Welcome({ name, age }) {
return Hello, {name}. Age: {age}
;
}
Lifecycle Methods
Class component methods that run at specific points in a component's lifecycle.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
componentDidUpdate(prevProps, prevState) {
if (this.state.date !== prevState.date) {
console.log('Time updated');
}
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return {this.state.date.toLocaleTimeString()};
}
}
React Ecosystem
React Router
Declarative routing for React applications.
npm install react-router-dom
import { BrowserRouter, Route, Link } from 'react-router-dom';
function App() {
return (
Home
About
);
}
Redux
Predictable state container for JavaScript apps.
npm install redux react-redux
// Action
const increment = () => ({ type: 'INCREMENT' });
// Reducer
const counter = (state = 0, action) => {
switch(action.type) {
case 'INCREMENT': return state + 1;
default: return state;
}
};
// Store
const store = createStore(counter);
// React Component
function Counter({ value, onIncrement }) {
return ;
}
// Connect to Redux
const ConnectedCounter = connect(
state => ({ value: state }),
dispatch => ({ onIncrement: () => dispatch(increment()) })
)(Counter);
Next.js
React framework for server-rendered applications.
npx create-next-app
// pages/index.js
export default function Home() {
return Home Page
;
}
// pages/about.js
export default function About() {
return About Page
;
}
Material-UI
Popular React UI component library.
npm install @mui/material @emotion/react @emotion/styled
import { Button, TextField } from '@mui/material';
function App() {
return (
<>
>
);
}
React Native
Build native mobile apps with React.
npx react-native init MyApp
import { View, Text, Button } from 'react-native';
function App() {
return (
Hello World!
);
}
GraphQL
Query language often used with React.
npm install @apollo/client graphql
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://api.example.com/graphql',
cache: new InMemoryCache()
});
client.query({
query: gql`
query GetBooks {
books {
title
author
}
}
`
}).then(result => console.log(result));
Practical Examples
Simple Counter
A basic counter demonstrating state management.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const increment = () => setCount(count + step);
const decrement = () => setCount(count - step);
const reset = () => setCount(0);
return (
Count: {count}
setStep(Number(e.target.value))}
/>
);
}
Fetching Data
Demonstrates data fetching with useEffect.
import { useState, useEffect } from 'react';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setUsers(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []); // Empty dependency array means run once
if (loading) return Loading...;
if (error) return Error: {error.message};
return (
{users.map(user => (
-
{user.name}
Email: {user.email}
Company: {user.company.name}
))}
);
}
Form Handling
Complete form with validation and submission.
import { useState } from 'react';
function LoginForm() {
const [formData, setFormData] = useState({
email: '',
password: ''
});
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
const validate = () => {
const newErrors = {};
if (!formData.email) newErrors.email = 'Email is required';
if (!formData.password) newErrors.password = 'Password is required';
else if (formData.password.length < 6) newErrors.password = 'Password must be at least 6 characters';
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = (e) => {
e.preventDefault();
if (validate()) {
setIsSubmitting(true);
// Simulate API call
setTimeout(() => {
console.log('Form submitted:', formData);
setIsSubmitting(false);
alert('Login successful!');
}, 1000);
}
};
return (
);
}
Conditional Rendering
Different ways to conditionally render content.
function UserGreeting({ isLoggedIn, user }) {
// 1. If-else statement
if (!isLoggedIn) {
return ;
}
// 2. Element variables
const message = user.unreadMessages > 0
? You have {user.unreadMessages} unread messages!
: You have no new messages.
;
// 3. Inline If with logical && operator
const welcomeAdmin = user.isAdmin &&
Admin User;
// 4. Inline If-Else with ternary operator
const lastLogin = user.lastLogin
? Last login: {user.lastLogin}
: First time login!
;
return (
Welcome back, {user.name}!
{welcomeAdmin}
{message}
{lastLogin}
);
}
function GuestGreeting() {
return (
Please sign in.
);
}
// Usage:
//