React and MongoDB project example

0 votes
57 views
added Feb 8 in React by lcjr First Warrant Officer (11,930 points)

To create a simple React backend editor and frontend component to handle fields like title, category, description, links, and embedding YouTube videos, you can follow these steps:

  1. Set up a basic React project.
  2. Create a backend server using a lightweight Node.js framework like Express.
  3. Use a simple database like MongoDB or Firebase to store the information.
  4. Implement CRUD (Create, Read, Update, Delete) operations for managing the data.
  5. Create frontend components for editing and displaying the data.

Below is a simplified example to get you started:

Backend (Node.js with Express and MongoDB)

// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(cors());
app.use(bodyParser.json());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/backend_editor', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// Define schema and model for the data
const articleSchema = new mongoose.Schema({
  title: String,
  category: String,
  subCategory: String,
  description: String,
  links: [String],
  youtubeEmbed: String,
});

const Article = mongoose.model('Article', articleSchema);

// CRUD routes
app.post('/api/articles', async (req, res) => {
  const { title, category, subCategory, description, links, youtubeEmbed } = req.body;
  const newArticle = new Article({
    title,
    category,
    subCategory,
    description,
    links,
    youtubeEmbed,
  });
  try {
    await newArticle.save();
    res.status(201).json(newArticle);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

app.get('/api/articles', async (req, res) => {
  try {
    const articles = await Article.find();
    res.json(articles);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Other CRUD routes for updating and deleting articles

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

 

Frontend (React)

1. Backend Editor Component

// EditorComponent.js
import React, { useState } from 'react';
import axios from 'axios';

const EditorComponent = () => {
  const [formData, setFormData] = useState({
    title: '',
    category: '',
    subCategory: '',
    description: '',
    links: ['', '', '', ''],
    youtubeEmbed: '',
  });

  const handleChange = (e, index) => {
    if (e.target.name === 'links') {
      const updatedLinks = [...formData.links];
      updatedLinks[index] = e.target.value;
      setFormData({ ...formData, links: updatedLinks });
    } else {
      setFormData({ ...formData, [e.target.name]: e.target.value });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post('/api/articles', formData);
      // Optionally, you can add success message or redirect to another page
    } catch (err) {
      console.error(err);
      // Handle error
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" name="title" value={formData.title} onChange={handleChange} placeholder="Title" required />
        <input type="text" name="category" value={formData.category} onChange={handleChange} placeholder="Category" required />
        <input type="text" name="subCategory" value={formData.subCategory} onChange={handleChange} placeholder="Sub-Category" required />
        <textarea name="description" value={formData.description} onChange={handleChange} placeholder="Description" required />
        {[0, 1, 2, 3].map((index) => (
          <input key={index} type="text" name="links" value={formData.links[index]} onChange={(e) => handleChange(e, index)} placeholder={`Link ${index + 1}`} />
        ))}
        <input type="text" name="youtubeEmbed" value={formData.youtubeEmbed} onChange={handleChange} placeholder="YouTube Embed" />
        <button type="submit">Save</button>
      </form>
    </div>
  );
};

export default EditorComponent;

 

2. Frontend Display Component

// DisplayComponent.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    const fetchArticles = async () => {
      try {
        const response = await axios.get('/api/articles');
        setArticles(response.data);
      } catch (err) {
        console.error(err);
        // Handle error
      }
    };

    fetchArticles();
  }, []);

  return (
    <div>
      {articles.map((article) => (
        <div key={article._id}>
          <h2>{article.title}</h2>
          <p>{article.category} - {article.subCategory}</p>
          <p>{article.description}</p>
          {article.links.map((link, index) => (
            <a key={index} href={link}>Link {index + 1}</a>
          ))}
          {article.youtubeEmbed && <div dangerouslySetInnerHTML={{ __html: article.youtubeEmbed }} />}
        </div>
      ))}
    </div>
  );
};

export default DisplayComponent;

 

Page or App.js

// App.js
import React from 'react';
import EditorComponent from './EditorComponent';
import DisplayComponent from './DisplayComponent';

const App = () => {
  return (
    <div>
      <h1>Backend Editor</h1>
      <EditorComponent />
      <h1>Articles</h1>
      <DisplayComponent />
    </div>
  );
};

export default App;

 

Ensure you have MongoDB running locally on the default port (27017), and then start your backend server (node server.js). After that, you can start your React frontend (npm start) to see the editor and display components in action. Remember to install necessary dependencies (axios, mongoose, express, cors, body-parser) via npm or yarn.

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...