DEV Community

Cover image for Build A Blog Website Using ReactJS and Firebase
Caffeine Code
Caffeine Code

Posted on • Updated on

Build A Blog Website Using ReactJS and Firebase

Welcome buddy ! This blog post will teach you how to build a blog site using React and Firebase.
First we will learn , Initial setup of Firebase.
and then we connect our project to firebase.
and third we will code our project.

so lets start First section

1. Setup of Firebase

  1. Go to firebase website and signup. and than go on to the firebase console and create new project.

Image description

Image description

  1. Now Enter the project name , and click on continue. it will lead you to next screen.

Image description

  1. click on continue and you will land on second screen where you can select analytics account if opted for google analytics on the previous screen and click continue.

Image description

Image description

  1. Your Firebase Project is ready. Now go to project setting to connect React Project to Firebase.

Image description

Image description

2. Build React app

  1. Go to your terminal and Create New React App using
npx create-react-app@5.0.0 Blog-React-app
cd Blog-React-app
npm start
Enter fullscreen mode Exit fullscreen mode
  1. Our react app is ready now we have to connect it to our firebase project. So first thing is to install firebase node modules in our project. you can run the following command to install the latest SDK:
npm install firebase
Enter fullscreen mode Exit fullscreen mode
  1. now lets create a file structure for blog website.
    Image description

  2. so first we create a firebase.js file in src folder. And copy Firebase configurations.

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

firebase.initializeApp({
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    projectId: "xxxxxxxxxxxxxxx",
    storageBucket: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
    messagingSenderId: "xxxxxxxxx",
    appId: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    measurementId: "xxxxx"
});

const fb = firebase;

export default fb;
Enter fullscreen mode Exit fullscreen mode
  1. Here, you can see i removed my project configurations. that is unique for every firbase project. So you have to go on your project setting and copy it and paste here.

Image description

  1. Now open App.js file and remove all extra lines of code
import React from "react";


function App() {
  return (

  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode
  1. Our Blogging website meanily works on four operations.1.Create Blog2. Show Blogs List 3. Read A Blog 4. Edit A Blog and last 5. Delete a Blog so lets create a Create.js file in blogs directory in Src directory. src/components/blogs/create.js first, we have to import database to our file. we will do that by this code.
import fb from '../firebase';
 db = fb.firestore()
const Blogs = db.collection('blogs');
Enter fullscreen mode Exit fullscreen mode

hire, Fb is the module which we initialize in firebase.js file. and fb.firestore() points to our database on firebase.
and the collection is a table of data. in which table you want to add new data.
and in firebase you don't have to create table, you can directly insert data and firebase automatically creates a new collection.
now, we will create a function to render our creation form. and take input from user to send it to database.

import {useState} from 'react';

const CreateBlog= () => {
    const [title , SetTitle] = useState("");
    const [body , SetBody] = useState("");

    const sub = (e) => {
        e.preventDefault();
        // Add data to the store
        Blogs.add({
            Title: title,
            Body: body,
            publish: false,
            published_on: fb.firestore.Timestamp.fromDate(new Date())
        })
        .then((docRef) => {
            alert("Data Successfully Submitted");
        })
        .catch((error) => {
            console.error("Error adding document: ", error);
        });
    }
    return (
    <div>

    </div>

    );
}

export default CreateBlog;
Enter fullscreen mode Exit fullscreen mode

here We have created two variables which are title and body. and intialize there value with black string. and when user click on submit button we will run a new function , which is named sub = (e) => {}.

<div>
        <form onSubmit={(event) => {sub(event)}}>    
            <input type="text" placeholder="Title" 
            onChange={(e)=>{SetTitle(e.target.value)}} required />

            <textarea  name="content" type="text" placeholder="write yoyr content here" 
            rows="10" cols="150" onChange={(e)=>{SetBody(e.target.value)}} required >
            </textarea>

            <button type="submit">Submit</button>
        </form>
    </div>
Enter fullscreen mode Exit fullscreen mode

so our complete file will look like this.

import {useState} from 'react';
import fb from '../firebase';
 db = fb.firestore()
const Blogs = db.collection('blogs');

const CreateBlog= () => {
    const [title , SetTitle] = useState("");
    const [body , SetBody] = useState("");

    const sub = (e) => {
        e.preventDefault();
        // Add data to the store
        Blogs.add({
            Title: title,
            Body: body,
            publish: false,
            published_on: fb.firestore.Timestamp.fromDate(new Date())
        })
        .then((docRef) => {
            alert("Data Successfully Submitted");
        })
        .catch((error) => {
            console.error("Error adding document: ", error);
        });
    }
    return (
    <div>
        <form onSubmit={(event) => {sub(event)}}>    
            <input type="text" placeholder="Title" 
            onChange={(e)=>{SetTitle(e.target.value)}} required />

            <textarea  name="content" type="text" placeholder="write yoyr content here" 
            rows="10" cols="150" onChange={(e)=>{SetBody(e.target.value)}} required >
            </textarea>

            <button type="submit">Submit</button>
        </form>
    </div>

    );
}

export default CreateBlog;

Enter fullscreen mode Exit fullscreen mode

now we will create a blogslist view , where can see all blogs' list.

import React, { useState, useEffect }from 'react'
import { Link } from "react-router-dom";
import fb from './firebase'


const db = fb.firestore()
const Blogs = db.collection('blogs');


const Bloglist = () => {
    const [blogslist, setblogs] = useState([]);

    useEffect(() => {
        // Subscribe to query with onSnapshot
        const unsubscribe = Blogs.limit(100).onSnapshot(querySnapshot => {
          // Get all documents from collection - with IDs
          const data = querySnapshot.docs.map(doc => ({
            ...doc.data(),
            id: doc.id,
          }));
          // Update state
          setblogs(data);
        });

        // Detach listener
        return unsubscribe;
      }, []);

    return (
        <div >

        <h2 className="w-full text-center font-bold text-xl">All blogs List</h2>

            {blogslist.map(blog=> (
                <div key={blog.id}>
    <p>Title : {blog.Title}</p>
    <p>body: {blog.Body} </p>
    <Link to={"/blog/"+blog.id}
        class="mr-2 bg-indigo-500 hover:bg-indigo-700 text-white font-bold py-1 px-2 border border-indigo-500 rounded"
        >View
    </Link>
    <Link to={"/blog/edit/"+blog.id}
        class="mr-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 border border-blue-500 rounded"
        >Edit
    </Link>
</div>          
            ))}
            ]]

    </div>
    );
  };

export default Bloglist;

Enter fullscreen mode Exit fullscreen mode

now we will add Delete button to list. so we create a delete function.

const Blogs = db.collection('blogs');

const DeleteBlog = (id)=> {
        Blogs.doc(id).delete().then(() => {
            alert("Document successfully deleted!");
        }).catch((error) => {
            console.error("Error removing document: ", error);
        });
    };
Enter fullscreen mode Exit fullscreen mode

after creating a function , we have to create a button which will call this function. and gives the id parameter to identify blog

<button 
                            onClick={()=> {DeleteBlog(blog.id)}} 
                        >delete</button>
Enter fullscreen mode Exit fullscreen mode

now complete bloglist.js file look like this.

import React, { useState, useEffect }from 'react'
import { Link } from "react-router-dom";
import fb from './firebase'


const db = fb.firestore()
const Blogs = db.collection('blogs');


const Bloglist = () => {
    const [blogslist, setblogs] = useState([]);

    const DeleteBlog = (id)=> {
        Blogs.doc(id).delete().then(() => {
            alert("Document successfully deleted!");
        }).catch((error) => {
            console.error("Error removing document: ", error);
        });
    };

    useEffect(() => {
        // Subscribe to query with onSnapshot
        const unsubscribe = Blogs.limit(100).onSnapshot(querySnapshot => {
          // Get all documents from collection - with IDs
          const data = querySnapshot.docs.map(doc => ({
            ...doc.data(),
            id: doc.id,
          }));
          // Update state
          setblogs(data);
        });

        // Detach listener
        return unsubscribe;
      }, []);

    return (
        <div >
        <h2 className="w-full text-center font-bold text-xl">All blogs List</h2>
            {blogslist.map(blog=> (
                <div key={blog.id}>
                    <p>Title : {blog.Title}</p>
                    <p>body: {blog.Body} </p>
                    <Link to={"/blog/"+blog.id}
                        class="mr-2 bg-indigo-500 hover:bg-indigo-700 text-white font-bold py-1 px-2 border border-indigo-500 rounded"
                        >View
                    </Link>
                    <Link to={"/blog/edit/"+blog.id}
                        class="mr-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-2 border border-blue-500 rounded"
                        >Edit
                    </Link>
                    <button 
                        onClick={()=> {DeleteBlog(blog.id)}} 
                    >delete</button>
                </div>
            ))}
    </div>
    );
  };

export default Bloglist;


Enter fullscreen mode Exit fullscreen mode

actually you can see we have already add two links in our list , which are View link and Edit link.

before creating View and edit page we have to take a look on our routers. so we will add routers tag in our app.js file

<Router>
      <Navbar/>
    <Routes>
        <Route exact path='/' element={<Home/>} />
        <Route exact path='/blog/' element={<Bloglist/>} />

        <Route path='/blog/create' element={<CreateBlog/>}  />
        <Route path='/blog/:id' element={<BlogView/>}  />
        <Route path='/blog/edit/:id' element={<BlogEdit/>}  />

    </Routes>
    </Router>
Enter fullscreen mode Exit fullscreen mode

we use Home, Bloglist , Createblog, BlogView and BlogEdit tags. so will import them from their files.

import CreateBlog from "./components/blogs/create";
import Bloglist from "./components/bloglist";
import BlogView from "./components/blogs/show";
import BlogEdit from "./components/blogs/edit";

import Home from "./components/pages/home";
import Navbar from "./components/temps/navbar";
Enter fullscreen mode Exit fullscreen mode

Now our complete app.js file will look like this

import CreateBlog from "./components/blogs/create";
import Bloglist from "./components/bloglist";
import BlogView from "./components/blogs/show";
import BlogEdit from "./components/blogs/edit";

import Home from "./components/pages/home";
import Navbar from "./components/temps/navbar";

import React from "react";
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';

function App() {
  return (
    <Router>
      <Navbar/>
    <Routes>
        <Route exact path='/' element={<Home/>} />
        <Route exact path='/blog/' element={<Bloglist/>} />

        <Route path='/blog/create' element={<CreateBlog/>}  />
        <Route path='/blog/:id' element={<BlogView/>}  />
        <Route path='/blog/edit/:id' element={<BlogEdit/>}  />

    </Routes>
    </Router>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now we will create Edit.js for blogEdit and show.js to BlogView.

  1. Show.js
import React, { useState }from 'react'
import { useParams } from "react-router-dom";


import fb from '../firebase';
const db = fb.firestore()
const Blogs = db.collection('blogs');


const BlogView = () => {
    const { id } = useParams();

    const [blog, setblog] = useState([]); 
    Blogs.doc(id).get().then((snapshot) => {
        const data = snapshot.data();
        setblog(data);
    });

    return (
        <div>
            <div className="w-full max-w-2xl mx-auto">       
                <h1 className="text-2xl">
                    <span><b>Title :</b></span>
                    <span>{blog.Title}</span>
                </h1>
                <p><b>Body :</b></p>
                <p>{blog.Body}</p>

            </div>            
        </div>
    );
};

export default BlogView;



Enter fullscreen mode Exit fullscreen mode
  1. Edit.js
import React, { useEffect, useState }from 'react'
import { useParams } from "react-router-dom";


import fb from '../firebase';
const db = fb.firestore()
const Blogs = db.collection('blogs');


const BlogEdit = () => {
    const { id } = useParams();

    const [title , SetTitle] = useState("");
    const [body , SetBody] = useState("");

    useEffect( (id)=> {
        Blogs.doc(id).get().then((snapshot) => {
            const data = snapshot.data();
            SetTitle(data.Title);
            SetBody(data.Body);
        });
    },[]);

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

        // Add data to the store
        Blogs.doc(id).update({
            Title: title,
            Body: body,
            last_Updated: fb.firestore.Timestamp.fromDate(new Date())
        })
        .then((docRef) => {
            alert("Data Successfully Updated");
        })
        .catch((error) => {
            console.error("Error adding document: ", error);
        });
    }
    return (
        <div>

        <form onSubmit={(event) => {sub(event)}}>    
            <input type="text" placeholder="Title"  value={title}
            onChange={(e)=>{SetTitle(e.target.value)}} required />

            <textarea  name="content" type="text" value={body}
            placeholder="write yoyr content here" 
            rows="10" cols="150" onChange={(e)=>{SetBody(e.target.value)}} required >
            </textarea>

            <button type="submit">Submit</button>
        </form>
        </div>
    );
};

export default BlogEdit;
Enter fullscreen mode Exit fullscreen mode

now save your files and run npm start.
And Your project is ready.
in this blog we will not discuss about styling.

You can read source code from git repo Click here

You can watch youtube video of this blog.
Watch

Feel free to ask any doubt in comment section.
Thank you for reading

Top comments (0)