Sunday, June 19, 2022
HomeWordPress DevelopmentThe right way to create a weblog web site with React &...

The right way to create a weblog web site with React & firebase -> Series2


Whats up dev neighborhood,

Welcome to this sequence the place we’re constructing running a blog web site with react and firebase.

Within the final tutorial we ready the environments and created the login and HomePage
Examine it out right here or Right here too

On this article we’re going to full out construct. Let’s put together the UI the place the consumer will add a picture and caption of the picture.

Create CreatePost.js file that can comprise the next codes.

import React, { useState } from "react";
import { useSelector } from "react-redux";
import { selectUser } from "../options/userSlice";
import { db } from "../utils/firebase";
import firebase from "firebase/compat/app";

const CreatePost = () => {
  const consumer = useSelector(selectUser);

  const [postTitle, setPostTitle] = useState("");
  const [imageURL, setimageURL] = useState("");

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

    db.assortment("posts").add({
      uid: consumer.uid,
      message: postTitle,
      displayName: consumer?.displayName,
      picture: imageURL,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });

    setPostTitle("");
    setimageURL("");
  };
  return (
    <div className="w-full mx-auto py-3 px-3 border bg-white  border-gray-300 rounded-md">
      <type className="mx-auto">
        <enter
          worth={postTitle}
          onChange={(e) => setPostTitle(e.goal.worth)}
          className="rounded-full w-full border outline-2 px-5 py-2 focus:outline-green-600"
          kind="textual content"
          placeholder="Enter Submit Caption"
        />
        <enter
          worth={imageURL}
          onChange={(e) => setimageURL(e.goal.worth)}
          className="rounded-full mt-6 w-full border outline-2 px-5 py-2 focus:outline-green-600"
          kind="textual content"
          placeholder="Enter Picture Url"
        />
        <button onClick={handleSubmit} className="hidden" kind="submit">
          Hidden Submit
        </button>
      </type>
    </div>
  );
};

export default CreatePost;
Enter fullscreen mode

Exit fullscreen mode

**Observe: **Our picture enter is a string that means that we’ll paste picture url from the web or some other supply.

Enter values from the enter discipline and press Enter Key and your knowledge can be submitted to the firestore database.

After we verify at our firebase firestore we will discover {that a} new assortment referred to as posts has been created.

Now we have to fetch that knowledge from the db to our webpage.

To fetch our knowledge we are going to make use of useEffect() hook. Let’s create feed.js file that can assist us fetch and maintain our knowledge.

import React, { useState, useEffect } from "react";
import { db } from "../utils/firebase";
import Submit from "./Submit";

perform Feed() {
  // fetch posts and retailer them in an array
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    db.assortment("posts")
      .orderBy("timestamp", "desc")
      .onSnapshot((snapshot) =>
        setPosts(snapshot.docs.map((doc) => ({ id: doc.id, knowledge: doc.knowledge() })))
      );
  }, []);
  return (
    <div className="feed">
      {posts.map((publish) => (
        <Submit
          key={publish.id}
          message={publish.knowledge.message}
          timestamp={publish.knowledge.timestamp}
          displayName={publish.knowledge.displayName}
          picture={publish.knowledge.picture}
          likes={publish.knowledge.likes}
          uid={publish.knowledge.uid}
        />
      ))}
    </div>
  );
}

export default Feed;
Enter fullscreen mode

Exit fullscreen mode

Observe: now we have used the map() perform as an alternative of forEach() ** perform to map all of the posts from our firestore assortment, it is because **map() is the brand new factor on the town 😊.

Now now we have fetched our knowledge from firestore, let’s create publish.js file that can deal with the publish particulars and show on the internet web page.

import React from "react";

perform Submit({ displayName, picture, timestamp, message }) {
  return (
    <div className="bg-white border border-gray-300 py-3 px-3 mt-3 mb-3 rounded-md">
      <div className="flex items-center justify-between border-b-2 pb-2">
        <div className="flex items-center space-x-3 ">
          <div className="text-center items-center pt-3  bg-green-600 text-white rounded-full w-12 h-12">
            {displayName[0]}
          </div>
          <div className="">
            <h3>{displayName}</h3>
            <p className="text-xs text-gray-500">
              {new Date(timestamp?.toDate()).toUTCString()}
            </p>
          </div>
        </div>
      </div>

      <div className="mt-3">
        <p>{message}</p>
      </div>

      <div className="mt-5">
        <img className="w-full h-56 " src={picture} alt="" />
      </div>

      <div className=" mt-3 flex justify-between items-center w-full">
        <div className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-green-600 py-1 px-2">
          <p>Like</p>
        </div>
        <div className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-green-600 py-1 px-2">
          <p>Remark</p>
        </div>
        <div className="cursor-pointer bg-gray-100 hover:bg-gray-200 text-green-600 py-1 px-2">
          <p>Share</p>
        </div>
      </div>
    </div>
  );
}

export default Submit;
Enter fullscreen mode

Exit fullscreen mode

Observe: we’re importing all of the props from feed.js file.

Now we’re achieved from sending out publish and fetching it from firestore. Let’s export our feed.js file to our HomePage.js file

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { login, logout, selectUser } from "../options/userSlice";
import { auth } from "../utils/firebase";
import CreatePost from "./CreatePost";
import Feed from "./Feed";
import Header from "./Header";

const HomePage = () => {
  const consumer = useSelector(selectUser);
  const dispatch = useDispatch();

  useEffect(() => {
    auth.onAuthStateChanged((userAuth) => {
      if (userAuth) {
        dispatch(
          login({
            e mail: userAuth.e mail,
            uid: userAuth.uid,
            displayName: userAuth.displayName,
          })
        );
      } else {
        dispatch(logout);
      }
    });
  }, [dispatch]);
  return (
    <>
      <Header />
      <div className="flex space-x-10 justify-between w-5/6 mx-auto mt-5">
        <div className="hidden h-40 bg-white rounded-md border border-1 border-gray-300 pb-5 md:flex flex-col items-center w-2/6 ">
          <img
            className=" rounded-t-md h-20 w-full"
            src="https://photos.unsplash.com/photo-1542831371-29b0f74f9713?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Y29kaW5nfGVufDB8fDB8fApercent3Dpercent3D&w=1000&q=80"
            alt="textual content"
          />
          <div className="text-center items-center pt-3 -mt-7 bg-green-600 text-white rounded-full w-12 h-12">
            {consumer?.displayName[0]}
          </div>
          <p className="mt-3">{consumer.displayName}</p>
        </div>
        <div className="mx-auto w-full">
          <CreatePost />
          <Feed />
        </div>
        <div className="hidden bg-white rounded-md border border-1 border-gray-300 pb-5 md:block py-4 px-2 w-2/6 h-80">
          <h2>Trending matters</h2>
          <div className="text-left items-center pt-3 space-y-5">
            <p className="text-sm text-gray-600">#Javascript</p>
            <p className="text-sm text-gray-600">#Java</p>
            <p className="text-sm text-gray-600">#Typescript</p>
            <p className="text-sm text-gray-600">#Python</p>
            <p className="text-sm text-gray-600">#Knowledge Science</p>
            <p className="text-sm text-gray-600">#Machine Studying</p>
          </div>
        </div>
      </div>
    </>
  );
};

export default HomePage;
Enter fullscreen mode

Exit fullscreen mode

Observe: we’re utilizing the house web page to model our utility so we will export our web page to the App.js file and deal with the authentication to point out the homepage if the consumer is just not logged-in.

Now let’s import our HomePage.js file to our App.js file.

import React, { useEffect } from "react";
import { Routes, Route } from "react-router-dom";
import HomePage from "./parts/HomePage";
import "./App.css";
import Login from "./parts/Login";
import { useDispatch, useSelector } from "react-redux";
import { login, logout, selectUser } from "./options/userSlice";
import { auth } from "./utils/firebase";

perform App() {
  const dispatch = useDispatch();
  const consumer = useSelector(selectUser);

  //validate and maintain the consumer loggedIn
  useEffect(() => {
    auth.onAuthStateChanged((userAuth) => {
      if (userAuth) {
        dispatch(
          login({
            e mail: userAuth.e mail,
            uid: userAuth.uid,
            displayName: userAuth.displayName,
            profilePic: userAuth.photoURL,
          })
        );
      } else {
        dispatch(logout);
      }
    });
  }, [dispatch]);
  return (
    <div className="">
      <Routes>
        {!consumer ? (
          <Route path="/" aspect={<Login />} />
        ) : (
          <Route path="/" aspect={<HomePage />} />
        )}
      </Routes>
    </div>
  );
}

export default App;
Enter fullscreen mode

Exit fullscreen mode

In App.js file now we have made use of react-router-dom to deal with our routes when the consumer is authenticated.
To put in react-router-dom use the next command

npm set up react-router-dom
Enter fullscreen mode

Exit fullscreen mode



Conclusion

We now have lastly created a whole running a blog web site with react and firebase. In our remaining construct on this sequence, we’re going to deploy it to firebase.

This text sequence was initially printed at melbite.com/create-blogging-web-with-react-firebase

You will discover extra of my articles on https://melbite.com

To get the supply code of this lovely utility verify my github

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments