How to Create a Responsive Web Page for Article Management Using React.js and PHP API

Senthil G

published September 10, 2024, 05:27:55 AM UTC

0
0
0
0
How to Create a Responsive Web Page for Article Management Using React.js and PHP API
3 min read

In today’s digital landscape, having a responsive web page for managing articles is crucial for providing a seamless user experience across various devices. Combining React.js for the frontend with a PHP API for the backend is a powerful approach to achieve this. Here’s a step-by-step guide to building a responsive article management system using React.js and a PHP API.

1. Setting Up the Development Environment

Frontend:

  • React.js: A popular JavaScript library for building user interfaces. It allows you to create dynamic and responsive web pages.
  • Bootstrap: A CSS framework that helps with responsive design.

Backend:

  • PHP: A server-side scripting language used for handling backend operations.
  • MySQL: A relational database management system for storing article data.

2. Creating the PHP API

Start by setting up a PHP API to handle CRUD (Create, Read, Update, Delete) operations for articles.

File Structure:

api/
  config.php (Database configuration)
  article.php (API endpoints for article management)
        

Example config.php:

setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
?>

Example article.php:

query('SELECT * FROM articles');
        $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($articles);
        break;
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        $stmt = $pdo->prepare('INSERT INTO articles (title, content) VALUES (:title, :content)');
        $stmt->execute(['title' => $data['title'], 'content' => $data['content']]);
        echo json_encode(['status' => 'Article created']);
        break;
    // Handle PUT and DELETE similarly
}
?>

3. Setting Up the React Frontend

File Structure:

src/
  components/
    ArticleList.js
    ArticleForm.js
  App.js
        

Example ArticleList.js:

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const ArticleList = () => {
    const [articles, setArticles] = useState([]);

    useEffect(() => {
        axios.get('http://localhost/api/article.php')
            .then(response => setArticles(response.data))
            .catch(error => console.error('Error fetching articles:', error));
    }, []);

    return (
        
Article List

                {articles.map(article => (
                    
{article.title}
{article.content}

                ))}
            

    );
};

export default ArticleList;
        

Example ArticleForm.js:

import React, { useState } from 'react';
import axios from 'axios';

const ArticleForm = () => {
    const [title, setTitle] = useState('');
    const [content, setContent] = useState('');

    const handleSubmit = (event) => {
        event.preventDefault();
        axios.post('http://localhost/api/article.php', { title, content })
            .then(response => {
                console.log(response.data);
                // Clear form or handle success
            })
            .catch(error => console.error('Error submitting article:', error));
    };

    return (
        
Add New Article
Title
 setTitle(e.target.value)}
                        required
                    />
Content
 setContent(e.target.value)}
                        required
                    >
Submit

    );
};

export default ArticleForm;
        

Example App.js:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import ArticleForm from './components/ArticleForm';
import ArticleList from './components/ArticleList';

const App = () => {
    return (
        


    );
};

export default App;
        

4. Styling for Responsiveness

Using Bootstrap, you can make sure that your layout adjusts to different screen sizes:

.container {
    margin-top: 20px;
}

@media (max-width: 768px) {
    .list-group-item {
        font-size: 14px;
    }
}
        

5. Testing and Deployment

Local Testing: Run your React app using npm start and ensure your PHP server is running. Test all functionalities including form submissions and data retrieval.

Deployment: Host your PHP API on a server and deploy your React app. Ensure the API endpoints are correctly configured in your React app.

Conclusion

By combining React.js with a PHP API, you can create a powerful, responsive web page for managing articles. This approach not only provides a smooth user experience but also leverages modern web technologies to ensure scalability and efficiency. Happy coding!

Comments