ReactJS Term Project: Tutorial

So What Even Is ReactJS, Anyway?

ReactJS is a JavaScript library created by Facebook with a focus on building UI elements
Components are written as what are essentially JavaScript functions that return HTML elements utilizing a markup variation of JavaScript known as JSX.
While React itself is somewhat barebones in nature, part of its selling point is that its simplicity allows for open-source plugins to provide the majority of possibilities with the framework.

What You'll Need To Download

How We Made Our Demo Page, In Case You Want To Follow Suit

You'll need to create two folders within the directory of your project, one named 'client' and one named 'server'. Using the terminal, navigate to the client folder and run the command:
npx create-react-app
This will create our ReactJS application. Next, navigate to your server folder, and run the command:
npm init
If you haven't already downloaded MongoDB, you'll need it to progress from this point. You will need to sign up for MongoDB and download MongoDB Compass for this.
Once you sign up for MongoDB, you want to create a new project. Then you make a new cluster, naming both the project and cluster whatever you’d like as it does not matter in the future.
Next, go onto Database Access and add a new database user. Whatever you decide to make, the username and password are up to you. Now you must go to Network access and add your current IP Address. Next, go back to the database tab and click the connect button. Then you will click on MongoDB Compass and copy the connection string, which should look something like this: mongodb+srv://NewStudent:
  @3344.d0869.mongodb.net/test
Now open up the MongoDB Compass you installed and create the connection using the string above with the username and password you name for the database user. Then we shall make a new Database. We will simply call these Database games and the collection games as well. Then you will want to create an index.js inside the server folder and begin making our express server. At the top of the index.js, you will need to write the following code. const express = require("express");
const app = express();
app.listen(3001, () => {
  console.log("Server running on port 3001..."); //Passes a port for our server to run on.
});
Now you want to write app.use(express.json()); This will send all of our front-end data to the back end in JSON format.
Afterward, we shall import the Mongoose library at the top of our program. const mongoose = require("mongoose"); You can create your database connection by grabbing it from the MongoDB website. Similar to how you connected before this time, you will connect from your application. First, copy the connection string, which should look like this. mongoose.connect(
“mongodb+srv://NewStudent:
@3344.d0869.mongodb.net/myFirstDatabase?retryWrites=true&w=majority”,
  {
    useNewUrlParser: true,
  }
);
Next, we will create our schema, and we do this by creating a folder inside our server folder called models. Inside that folder, we will create a new file called Game.js. As before, we will import the Mongoose library. I will post the complete schema below. const mongoose = require("mongoose");
const GamesSchema = new mongoose.Schema({
  gameImage: {
    type: String,
    required: true,
  },
  gameName: {
    type: String,
    required: true,
  },
  gameRating: {
    type: Number,
    required: true,
  },
  gameDifficulty: {
    type: String,
    required: true,
  },
  gamePublisher: {
    type: String,
    required: true,
  },
  gameESRB: {
    type: String,
    required: true,
  },
  gameDescription: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("Games", GamesSchema);
This schema serves as the skeleton of our database. In our index.js, we will load this by grabbing it with the following code. const GameModel = require("./models/Games"); We shall make a route in our index.js to insert information into our database. But before doing so, we will need to install cors, using the above command. app.post("/insert", async (req, res) => {
  const game = new GameModel({
    gameImage: req.body.gameImage,
    gameName: req.body.gameName,
    gameRating: req.body.rating,
    gameDifficulty: req.body.gameDifficulty,
    gamePublisher: req.body.gamePublisher,
    gameESRB: req.body.gameESRB,
    gameDescription: req.body.gameDescription,
  });
  try {
    await game.save();
    res.send("inserted data");
  } catch (err) {
    console.log(err);
  }
});
We will finally begin working on our React application.
Open up your client folder and the server folder. There are quite a few files created from installing libraries that we will not be using, so the following files can all safely be deleted at this point: Make sure to erase any information in the client folder’s index.js and app.js that deals with these files if you delete them.
Inside our App.js, you will create a function called App. Here we will make some of our JSX, HTML written inside Javascript. We will be using React Hooks and States here.
To summarize it very plainly, it is where our data will be saved and sent back to our database to be held.
function App() {
  const [gameImage, setGameImage] = useState("");
  const [gameName, setGameName] = useState("");
  const [gameDescription, setGameDescription] = useState("");
  const [rating, setRating] = useState(0);
  const [gameDifficulty, setGameDifficulty] = useState("");
  const [gamePublisher, setGamePublisher] = useState("");
  const [gameESRB, setGameESRB] = useState("");
  const [newGameName, setNewGameName] = useState("");
<div className="App">
    <h1>3344 Term Project>
    <label>Game Image<label>
    <input
      type="text"
      onChange={(event) => {
        setGameImage(event.target.value);
      }}
    />
    <label>Game Name<label>
    <input required
      type="text"
      onChange={(event) => {
        setGameName(event.target.value);
      }}
    />
    <label>Game Rating<label>
    <input required
      type="number"
      onChange={(event) => {
        setRating(event.target.value);
      }}
    />
    <label>Game's Difficulty<label>
    <input required
      type="text"
      onChange={(event) => {
        setGameDifficulty(event.target.value);
      }}
    />
    <label>Game's Publisher<label>
    <input required
      type="text"
      onChange={(event) => {
        setGamePublisher(event.target.value);
      }}
    />
    <label>Game's ESRB Rating<label>
    <input required
      type="text"
      onChange={(event) => {
        setGameESRB(event.target.value);
      }}
    />
    <label>Game Description<label>
    <input required
      type="text"
      onChange={(event) => {
        setGameDescription(event.target.value);
      }}
    />
After doing this, we will install Axios, using the terminal command above. Be sure to import it at the top of your file.
import Axios from "axios"; Then, you will put the following code at the top of your server index.js: const cors = require("cors"); Now we will create a function that will send these to the database. We will put this inside our function App(): const addToList = () => {
  Axios({
    method: "post",
    url: "http://localhost:3001/insert",
    headers: {},
    data: {
      gameImage: gameImage,
      gameName: gameName,
      rating: rating,
      gameDifficulty: gameDifficulty,
      gamePublisher: gamePublisher,
      gameESRB: gameESRB,
      gameDescription: gameDescription,
    },
  });
};
We will go back to our server’s index.js and create a new route to read the data from our database and post it for us. app.get("/read", async (req, res) => {
  GameModel.find({}, (err, result) => {
    if (err) {
      res.send(err);
    }
    res.send(result);
  });
});
We will be using another hook in our App.js, so go to the top of your document and make sure it looks like this.
import { useState, useEffect } from "react"; And in our Function App(), We will put the following code. useEffect(() => {
  Axios.get("http://localhost:3001/read").then((response) => {
    setGameList(response.data);
  });
}, []);
And above this, we will create another state. const [gameList, setGameList] = useState([]); Now we will write the JSX to make the information from our database appear. This will contain some extra information, but it’s okay since it’ll come up soon. {gameList.map((val, key) => {
  return (
    <div className="databaseEntry" key={key}>
      <img className="entryImage" src={val.gameImage} />
       <h1 className="entryHeader">{val.gameName}</h1>
      <p className="entryInfo">
        {val.gameDescription}
        {val.gameRating} {val.gameDifficulty} {val.gamePublisher}{" "}
        {val.gameESRB}
      </p>
      <input type="text"
        placeholder="Update Game Name..."
        onChange={(event) => {
          setNewGameName(event.target.value);
        }}
      />
      <button className="entryBtn" onClick={() => updateGame(val._id)}>
        Update
      <button>
      <button className="entryBtn2" onClick={() => deleteGame(val._id)}>
        Delete
      <button>
    </div>
  ); })}
There were many added bits of code on that last portion, but as said before, it will all be necessary for the following codes.
We will make another Axios request for the update code, so put the following code. const updateGame = (id) => {
  Axios({
    method: "PUT",
    url: "http://localhost:3001/update",
    params: {
      id: id,
      newGameName: newGameName,
    },
  });
};
Returning to the back end, we will add the following code inside the server folder’s Index.JS app.put("/update", async (req, res) => {
  const newGameName = req.body.newGameName;
  const id = req.body.id;
  try {
    await GameModel.findById(id, (err, updatedGame) => {
      updatedGame.gameName = newGameName;
      updatedGame.save();
      res.send("Successfully updated");
    });
  } catch (err) {
    console.log(err);
  }
});
And while we are here, we will make the back-end version for our Delete button, so you insert the code below. app.delete("/delete/:id", async (req, res) => {
  const id = req.params.id;
  await GameModel.findByIdAndRemove(id).exec();
  res.send("Successfully deleted");
});
Now returning to the client-side, we will make the Axios request to delete states, so below the update Axios, add the following code. const deleteGame = (id) => {
  Axios.delete(`http://localhost:3001/delete/${id}`, {});
};
And with that, you have finished making an application that uses React utilizing the MERN stack.

In Conclusion

ReactJS is a powerful UI-building framework whose expandability makes it one of the most worthwhile web development libraries to learn in this day and age, and its simplicity makes it flow seamlessly with most other libraries of its kind.

References