Skip to navigation

ReactJS Code Structure

This is a React.js project structure, it follows a modular, scalable, and maintainable structure.

The goal here is to serve as a collection of resources and best practices when developing React applications. It is supposed to showcase solving most of the real-world problems of an application in a practical way and help developers write better applications.

Project Structure

📂 reactjs-app
├── 📂 src
│ ├── 📂 api # API call functions
│ ├── 📂 components # Reusable UI components
│ ├── 📂 pages # Page-level components (Views)
│ ├── 📂 context # Global state management (React Context)
│ ├── 📂 hooks # Custom React hooks
│ ├── 📂 styles # Global and component styles
│ ├── 📄 App.tsx # Main App component
│ └── 📄 index.tsx # Entry point (renders React app)
├── 📂 public # Static assets (index.html, images, etc.)
├── 📄 .env # Environment variables
├── 📄 package.json # Dependencies and scripts
└── 📄 README.md # Project documentation


📂src/api - API Calls

Purpose: Centralized API communication using fetch or axios.

📄src/api/messageApi.ts

import axios from 'axios';
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:3000';
export const sendMessage = async (text: string, userId: string) => {
try {
const response = await axios.post(`${API_BASE_URL}/send`, { text, userId });
return response.data;
} catch (error) {
console.error('Error sending message:', error);
throw error;
}
};

📂src/components - Reusable UI Components

Purpose: Contains button, input, modal, etc. components.

📄src/components/Button.tsx

import React from 'react';
interface ButtonProps {
text: string;
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ text, onClick }) => {
return <button onClick={onClick} className="btn">{text}</button>;
};
export default Button;

📂src/pages - Page Components

Purpose: Page-level components that render entire views.

📄src/pages/Home.tsx

import React, { useState } from 'react';
import { sendMessage } from '../api/messageApi';
import Button from '../components/Button';
const Home: React.FC = () => {
const [message, setMessage] = useState('');
const [userId, setUserId] = useState('');
const [response, setResponse] = useState('');
const handleSendMessage = async () => {
try {
const result = await sendMessage(message, userId);
setResponse(result.status);
} catch (error) {
setResponse('Error sending message');
}
};
return (
<div className="container">
<h1>Send Message</h1>
<input type="text" placeholder="User ID" value={userId} onChange={(e) => setUserId(e.target.value)} />
<input type="text" placeholder="Message" value={message} onChange={(e) => setMessage(e.target.value)} />
<Button text="Send" onClick={handleSendMessage} />
<p>{response}</p>
</div>
);
};
export default Home;

📂src/context - Global State Management

Purpose: Manages global state using React Context API.

📄src/context/MessageContext.tsx

import React, { createContext, useState, ReactNode } from 'react';
interface MessageContextType {
message: string;
setMessage: (message: string) => void;
}
export const MessageContext = createContext<MessageContextType | undefined>(undefined);
export const MessageProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [message, setMessage] = useState('');
return (
<MessageContext.Provider value={{ message, setMessage }}>
{children}
</MessageContext.Provider>
);
};

📂src/hooks - Custom Hooks

Purpose: Encapsulates reusable logic.

📄src/hooks/useMessage.ts

import { useContext } from 'react';
import { MessageContext } from '../context/MessageContext';
const useMessage = () => {
const context = useContext(MessageContext);
if (!context) {
throw new Error('useMessage must be used within a MessageProvider');
}
return context;
};
export default useMessage;

📂src/styles - Styling

Purpose: Global styles and component-specific CSS.

📄src/styles/global.css

body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 500px;
margin: auto;
padding: 20px;
}
.btn {
background-color: #007bff;
color: white;
padding: 10px;
border: none;
cursor: pointer;
}

📄src/App.tsx - Main App Component

Purpose: Wraps the entire application and includes global state providers.

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Home from './pages/Home';
import { MessageProvider } from './context/MessageContext';
const App: React.FC = () => {
return (
<MessageProvider>
<Router>
<Routes>
<Route path="/" element={<Home />} />
</Routes>
</Router>
</MessageProvider>
);
};
export default App;

📄src/index.tsx - Application Entry Point

Purpose: Renders the React app into the DOM.

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles/global.css';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

📄.env - Environment Variables

REACT_APP_API_BASE_URL=http://localhost:3000

Reference Websites