Multiple ways: How you can integrate React, React hooks with Firebase? π
This guide has some steps to get information from a Firebase's database about animals π―π¦πΆπ± using React.js and React Hooks.
Nowadays, React.js & React hooks are becoming very popular and used in a lot of applications and different purposes. On this occasion, I'd like to share steps to help us to integrate a React.js web app with Firebase.
Pre-requisites
- Node.js (>= 14 version) installed.
- Have a Firebase project (without any database) created.
- Have a basic React.js & Firebase's knowledge.
Steps
- Create our database in Cloud Firestore
- Firebase configuration
- Prepare our React app with Firebase
- Create a new component: Animal
- Ways to Integrate React with Firebase
Create our database in Cloud Firestore
Cloud Firestore is a cloud-hosted, NoSQL database that your iOS, Android, and web apps can access directly via native SDKs - Google
- Structure our database.
We'll create a collection animals with many documents (animal) for example tiger π―, giraffeπ¦, dogπΆ, catπ±, etc.
For example:
[
{
"id":"2BmqU3soV8IA3juUf8lx",
"name":"Dog",
"image":"https://images.unsplash.com/photo-1534361960057-19889db9621e?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=1050&q=80",
"photoBy":"Photo by Joe Caione on Unsplash"
},
{
"id":"9g5kzBcXoP33BoHpiTTq",
"name":"Tiger",
"image":"https://images.unsplash.com/photo-1615551298862-0795063e3f1e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1051&q=80",
"photoBy":"Photo by Kartik Iyer on Unsplash"
}
]
Firebase configuration
b. Firebase configuration
When we create a Firebase's project we can access to configuration.
Now, we should create our web app** on Firebase: hashnode-animals-react.
- Click Register App
- Get our Firebase configuration for our web app.
For security purposes, I've hidden my credentials π.
Prepare our React app with Firebase
Create a React.js app + Firebase dependency
Fortunately, we can use create react app to create our React.js apps easily.
npx create-react-app firebase-react-hooks
cd firebase-react-hooks
npm i firebase
Firebase configuration file.
We need to create a new file where we'll put our Firebase configuration: firebaseConfig.js
. (Note.- You need to replace your Firebase credentials here.)
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
// Firestore
import "firebase/firestore";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "hashnode-animals-react.firebaseapp.com",
projectId: "hashnode-animals-react",
storageBucket: "hashnode-animals-react.appspot.com",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export { db };
CSS styles
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&family=Roboto:wght@100;300;400;500;700&display=swap');
:root {
--bg-primary: #dee0e6;
--bg-secondary: #10405B;
--bg-accent: #443D3B;
--text-primary: #000;
--text-secondary: #dee0e6;
--text-accent: #503a65;
}
* {
margin: 0;
padding: 0;
}
body {
background-color: var(--bg-primary);
color: var(--text-accent);
font-family: 'Open Sans', sans-serif;
}
h1 {
margin: 1em;
}
h2 {
margin: 0.5em;
}
h1,
h2 {
font-family: 'Roboto', sans-serif;
font-weight: 700;
text-align: center;
}
section {
margin: 1.5em 0;
}
.animals {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: space-around;
gap: 1em;
padding: 10px;
}
.animal {
background-color: var(--bg-secondary);
box-shadow: 3px 3px var(--bg-accent);
color: var(--text-primary);
border-radius: 10px;
padding: 10px;
width: 100%;
}
.animal-photoBy {
color: var(--text-secondary);
font-size: 0.7rem;
text-align: center;
}
.animal-image {
border-radius: 10px;
width: 100%;
}
.animal-name {
color: var(--text-secondary);
font-family: 'Roboto', sans-serif;
font-size: 1.5em;
font-weight: 700;
text-align: center;
}
.container {
padding: 10px;
}
@media (min-width: 580px) {
.animal {
width: 270px;
}
}
Create a new component Animal
This component will help us to show information about all animals.
// src/components/Animal.js
function Animal({ id, name, image, photoBy }) {
return (
<div className="animal" id={id}>
<img className="animal-image"
src={image}
alt={`It's an image about a ${name}`}
/>
<div className="animal-body">
<p className="animal-name">{name}</p>
</div>
<div className="animal-footer">
<p className="animal-photoBy">{photoBy}</p>
</div>
</div>
);
}
export default Animal;
Ways to integrate React with Firebase
For Firebase integration with our web app in React, we'll work in three ways:
- Using Firebase SDK + React Hooks.
- Using Firebase SDK + Create our custom hook in React.js.
- Using Firebase SDK + react-firebase-hook dependency.
Every solution or way to solve this integration. We are going to create a new React component like
Animals
,AnimalsCustomHook
, andAnimalsFirebaseHook
. On another hand, the collection name isanimals
for all cases.
Let's start. π
a. Using Firebase SDK + React Hooks.
// src/components/Animals.js
import { db } from "../firebaseConfig";
import { useEffect, useState } from "react";
import Animal from "./Animal";
function Animals() {
const [animals, setAnimals] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const firebaseAnimals = [];
db.collection("animals")
.get()
.then((querySnapshot) => {
setLoading(true);
querySnapshot.docs.forEach((doc) => {
firebaseAnimals.push({
id: doc.id,
...doc.data()
});
});
setAnimals(firebaseAnimals);
setLoading(false);
});
}, []);
return (
<section>
<h2>Firebase SDK</h2>
{loading && <span>Collection: Loading...</span>}
{!loading && animals && (
<div className="animals">
{animals.map(({ id, name, image, photoBy }) =>
<Animal
key={id}
id={id}
name={name}
image={image}
photoBy={photoBy}
/>
)}
</div>
)}
</section>
);
}
export default Animals;
Now, we can use our new Animals
components in App.js
.
import Animals from "./components/Animals";
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Animals</h1>
<main className="container">
<Animals />
</main>
</div>
);
}
Result
b. Using Firebase SDK + Create our custom hook in React.js.
From React 16.8, we can use Hooks also we can create our custom hooks only we need to create a function with a prefix use
.
Now, we create our custom hook useAnimals
for this purpose we'll "extract" our previous logic in another function with the hooks useState
and useEffect
.
// src/hooks/useAnimals.js
import { db } from "../firebaseConfig";
import { useEffect, useState } from "react";
function useAnimals() {
const [animals, setAnimals] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const firebaseAnimals = [];
db.collection("animals")
.get()
.then((querySnapshot) => {
setLoading(true);
querySnapshot.docs.forEach((doc) => {
firebaseAnimals.push({
id: doc.id,
...doc.data()
});
});
setAnimals(firebaseAnimals);
setLoading(false);
});
}, []);
return [animals, loading];
}
export default useAnimals;
Therefore, we can use this hook in any component. We'll create a new component AnimalsCustomHook
.
// src/components/AnimalsCustomHook.js
import useAnimals from "../hooks/useAnimals";
function AnimalsCustomHook() {
const [animals, loading] = useAnimals();
return (
<div>
<h2>Firebase SDK + Custom Hook "useAnimals"</h2>
{loading && <p>Loading data from Firebase...</p>}
{animals !== null && animals.length > 0 && (
<div className="animals">
{animals.map(({ id, name }) => {
return (
<span className="animal" key={id}>
{name}
</span>
);
})}
</div>
)}
{animals === null && animals.length <= 0 && <p>Empty list</p>}
</div>
);
}
export default AnimalsCustomHook;
Now, we can use our new AnimalsCustomHook
component in App.js
.
import AnimalsCustomHook from "./components/AnimalsCustomHook";
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Animals</h1>
<main className="container">
<AnimalsCustomHook />
</main>
</div>
);
}
Result
c. Using Firebase SDK + react-firebase-hook
dependency.
Another way to work with Firebase is using the react-firebase-hook
dependency. We need to install this dependency.
npm i react-firebase-hooks
With the react-firebase-hook
dependency installed, we can use one new hook: useCollection
. It receives as a parameter our collection animals
.
// src/components/AnimalsFirebaseHook.js
import { db } from "../firebaseConfig";
import { useCollection } from "react-firebase-hooks/firestore";
import Animal from "./Animal";
function AnimalsFirebaseHook() {
const [value, loading, error] = useCollection(db.collection("animals"));
return (
<section>
<h2>Firebase SDK + react-firebase-hooks "useCollection"</h2>
{error && <strong>Error: {JSON.stringify(error)}</strong>}
{loading && <span>Collection: Loading...</span>}
{value && (
<div className="animals">
{value.docs.map((doc) => {
const animal = {
id: doc.id,
...doc.data()
};
return (
<Animal key={animal.id}
id={animal.id}
name={animal.name}
image={animal.image}
photoBy={animal.photoBy}
/>
);
})}
</div>
)}
</section>
);
}
export default AnimalsFirebaseHook;
Now, we can use our new AnimalsFirebaseHook
component in App.js
.
import AnimalsFirebaseHook from "./components/AnimalsFirebaseHook";
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Animals</h1>
<main className="container">
<AnimalsFirebaseHook />
</main>
</div>
);
}
Result
Conclusions
As we have seen, there are many ways to integrate our React app with Firebase (Firebase SDK, React Hooks, and external libraries like react-firebase-hooks
) but the most important thing is that we can get the same result but with tools.
Thanks for your reading and time! I appreciate it.
See you until the next article!π