DEV Community

Blaine Yilmaz
Blaine Yilmaz

Posted on

How to create a forum in React

First, create a project with Vite:

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

After clean up, the project tree should looks like this:

├── client
  ├── node_modules
  ├── package.json
  ├── package-lock.json
  ├── public
  ├── src
    ├── App.jsx
    ├── index.css
    └── main.jsx
  ├── .gitignore
  ├── index.html
  └── vite.config.js
Enter fullscreen mode Exit fullscreen mode

Add this boilerplate to App.jsx. This should print the input values at the browser console:

import { useState } from "react";

function NewTopic() {

  const [title, setTitle] = useState(String);
  const [content, setContent] = useState(String);

  const Submit = (e) => {
    e.preventDefault();

   console.log(title, content)
  };

  return (
    <>
      <form onSubmit={Submit}>
        <input onChange={(e) => setTitle(e.target.value)} value={title} />
        <textarea onChange={(e) => setContent(e.target.value)} value={content} />
        <button type="submit">Create</button>
      </form>
    </>
  )
}

export default NewTopic;
Enter fullscreen mode Exit fullscreen mode

For sending the input data to a server, we'll use Axios library:

import axios from 'axios';

const Submit = (e) => {
    e.preventDefault();

    try {
      axios.post('http://localhost:3001/createPost', { title, content })
    } catch (error) {
      console.log(error);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Now create a Node server with Express.js library:

server.js

const cors = require('cors');
const express = require('express');
const app = express();
const server = require('http').createServer(app);

app.use(cors());
app.use(express.json());

server.listen(3001);
Enter fullscreen mode Exit fullscreen mode

The current project tree should looks like this:

├── .gitignore
├── index.html
├── package.json
├── package-lock.json
├── public
├── server.js
├── src
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
└── vite.config.js
Enter fullscreen mode Exit fullscreen mode

To keep our input data in one place, we'll use Mongo Database.
To get your own Mongo Database URL fallow this url.
Add all the Mongoose library functionalities to the server.js:

const mongoose = require('mongoose');
const { Schema } = mongoose;

mongoose.connect("mongodb+srv://username:password@cluster0.ufesskg.mongodb.net/forum-database");

const databaseSchema = new Schema({
  title: String,
  content: String
});

const Post = mongoose.model('Post', databaseSchema);
Enter fullscreen mode Exit fullscreen mode

Then, to give a response to coming request from React-side, create an endpoint in server.js:

app.post('/createPost', (req, res) => {
  Post.create({
    title: req.body.title,
    content: req.body.content
  });
});
Enter fullscreen mode Exit fullscreen mode

Screenshot from https://cloud.mongodb.com

The above code is just creates post. Now, return all posts to React-side for creating a simple forum:

app.post('/createPost', (req, res) => {
  Post.create({
    title: req.body.title,
    content: req.body.content
  });

  Post.find().then(PostFind => {
    var allData = PostFind;

    return res.json({ allData });
  });
});
Enter fullscreen mode Exit fullscreen mode

Now, back to the React-side to fetch res.json({ allData }); response with Axios.

We'll use Javascript map function, because we must list all the data to line down as column.

The final React-side code:

import { useState } from "react";
import axios from 'axios';

const NewTopic = () => {

  const [title, setTitle] = useState(String);
  const [content, setContent] = useState(String);
  const [allData, setAllData] = useState(null);

  const Submit = (e) => {
    e.preventDefault();

    try {
      axios.post('http://localhost:3001/createPost', { title, content }).then(TheResponse => {
        setAllData(TheResponse.data.allData);
      });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <form onSubmit={Submit}>
        <input onChange={(e) => setTitle(e.target.value)} value={title} />
        <textarea onChange={(e) => setContent(e.target.value)} value={content} />
        <button type="submit">Create</button>
      </form>

      <div>
        {
          allData.map((mapAllData) => (
            <div>
              <p>Title: {mapAllData.title} ||||||||||| Content: {mapAllData.content}</p>
            </div>
          ))
        }
      </div>
    </>
  )
}

export default NewTopic;
Enter fullscreen mode Exit fullscreen mode

If you'll have encounter an error, remove the "type": "module", line from the package.json.

Don't forget running both of express server and React-side client:
node server.js
and for React:
npm run dev

https://github.com/Blainegith/devto-react-forum

Top comments (0)