Build A Blog Website Using ReactJS and Firebase
Tags: react, firebase, javascript, webdev
Published: 2022-01-31 07:27:33

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.

{% embed https://www.youtube.com/embed/GERuklicI8k %}

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vf6dc0spk6tvmiuymybp.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sx4xrf8gey31yy35juok.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dy8prqlek9j4ki2jj0l.png)

3. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v0ohbswru6d8d60425rx.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b9vigv8360n9sc7210us.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xwzx0ptz6vsnvbe1h45c.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ei8ielkio2lh1pxuu0ay.jpg)

## 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
```
2. 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
```
3. now lets create a file structure for blog website.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxxg37v171flmywibxp3.png)

4. 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;
```
5. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdfq002iw9tenqh0jkye.jpg)

6. Now open `App.js` file and remove all extra lines of code

```
import React from "react";


function App() {
  return (
    
  );
}

export default App;

```

7. Our Blogging website meanily works on four operations.`1.Create Blog ``2. 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');
```

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;
```
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>
```

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;

```
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;

```
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);
        });
    };
```
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>
```
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;


```

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>
```
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";
```
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;

```
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;



```
2. `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;
```

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](https://github.com/VipinBansal-Youtube/Blog-website-Using-Reactjs-and-Firebase)

You can watch youtube video of this blog.
[Watch](https://youtu.be/GERuklicI8k)

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