Sitemap

Firebase blog application with react native

4 min readJan 25, 2022

--

Step 1 : In this step we will set up firebase

Press enter or click to view image in full size
Click on Add project
Press enter or click to view image in full size
Enter a project name
Press enter or click to view image in full size
Disable / enable google analytics based on your requirement and click on “Create Project”
Press enter or click to view image in full size
Click on Web icon
Press enter or click to view image in full size
Register the application , copy and store the code somewhere and move forward with the app
Press enter or click to view image in full size
Now go to authentication tab and click on Get Started
Press enter or click to view image in full size
Select Email/password as provider
Press enter or click to view image in full size
Go to firestore database and click on create database
Press enter or click to view image in full size
Start in production -> Next -> Move forward
Press enter or click to view image in full size
Start a collection
Press enter or click to view image in full size
Collection should look like this

Now start an expo app.

Run -> expo init firebaseblog

Required packages -> firebase , @react-navigation/native , @react-navigation/native-stack .

Create a folder name it Component and create new files Card.js , Createpost.js , Home.js , Login.js .

Card.js

import { View, Text, StyleSheet } from 'react-native';import React from 'react';export default function Card({title,authorName,description}) {return (<View style={styles.card_container}><View style={styles.upperhalf}><Text style={{fontSize:22}}>{title}</Text><Text style={{fontSize:22}}>X</Text></View><View style={styles.lowerhalf}><Text>{description}</Text><Text>{`@ ${authorName}`}</Text></View></View>);}const styles = StyleSheet.create({card_container:{backgroundColor:'#23C4ED',margin:5,borderRadius:10,},upperhalf:{flex:1,flexDirection:'row',justifyContent:'space-between',marginHorizontal:5,},lowerhalf:{backgroundColor:'#fff',margin:2,borderRadius:10,}})

Createpost.js

import { View ,TextInput, StyleSheet, Button} from 'react-native';import React, { useState } from 'react';import { addDoc, collection } from 'firebase/firestore';import { auth, db } from '../firebase';export default function Createpost({navigation}) {const[posttitle,setPosttitle] = useState()const[description,setdescription] = useState()const postref = collection(db,"posts")const addpost = async()=>{await addDoc(postref,{title:posttitle,description:description,authorName:auth.currentUser.email})alert('post added')navigation.navigate('Home')}return (<View style={styles.textareacontainer}><TextInput style={styles.texttitle} value={posttitle} onChangeText={(posttext)=>setPosttitle(posttext)} placeholder='Enter title'/><TextInput style={styles.textdescription} value={description} onChangeText={(postdesc)=>setdescription(postdesc)} placeholder='Enter description'/><View style={styles.submitbutton}><Button title='Submit Post' onPress={addpost}/></View></View>);}const styles = StyleSheet.create({textareacontainer:{justifyContent:'center',backgroundColor:'#fff',padding:10},texttitle:{marginTop:50,padding:20,borderWidth:2,borderColor:'#FF6666',borderRadius:20},textdescription:{height:150,marginTop:12,borderWidth:2,borderColor:'#FF6666',borderRadius:20,padding:10},submitbutton:{marginTop:15}})

Home.js

import { View, Text,StyleSheet,SafeAreaView,ScrollView, Button } from 'react-native';import React, { useEffect, useState } from 'react';import Card from './Card';import { collection, doc, getDocs } from 'firebase/firestore';import { db } from '../firebase';export default function Home({navigation}) {const [blogpost,setBlog] = useState([])const postref = collection(db,"posts")useEffect(()=>{const getPost=async()=>{const querySnapshot = await getDocs(postref);setBlog(querySnapshot.docs.map((doc)=>({...doc.data(),id:doc.id})))}getPost()})return (<SafeAreaView style={styles.container}><Button title='Add A Post' onPress={()=>navigation.navigate('Createpost')}/><ScrollView>{blogpost.map((post)=>(<Card title={post.title} authorName={post.authorName} description={post.description}/>))}</ScrollView></SafeAreaView>);}const styles = StyleSheet.create({container: {flex: 1,backgroundColor: '#fff',}});

Login.js

import { View, Text ,KeyboardAvoidingView,TextInput,StyleSheet,TouchableOpacity} from 'react-native';import React, { useState } from 'react';import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth';import { auth } from '../firebase';export default function Login({navigation}) {const [email,setEmail] = useState()const [password,setPassword] = useState()const handleRegister = ()=>{createUserWithEmailAndPassword(auth,email,password).then((userCredential)=>{const user = userCredential.user;alert(`Welcome ${user.email}`)navigation.navigate('Home')}).catch((error)=>alert(error.message))}const handleSignIn = ()=>{signInWithEmailAndPassword(auth,email,password).then((userCredential)=>{const user = userCredential.user;alert(`Welcome back ${user.email}`)navigation.navigate('Home')}).catch((error)=>alert(error.message))}return (<KeyboardAvoidingView behavior='padding' style={styles.container}><View style={styles.inputContainer}><TextInput style={styles.input} value={email} onChangeText={(text)=>setEmail(text)} placeholder='Enter email'/><TextInput style={styles.input} value={password} onChangeText={(text)=>setPassword(text)} placeholder='Enter password' secureTextEntry/></View><View style={styles.buttonContainer}><TouchableOpacity style={styles.buttons} onPress={handleSignIn}><Text style={{alignSelf:'center',color:'white'}}>Login</Text></TouchableOpacity><TouchableOpacity style={styles.buttons} onPress={handleRegister}><Text style={{alignSelf:'center',color:'white'}}>Register</Text></TouchableOpacity></View></KeyboardAvoidingView>);}const styles = StyleSheet.create({container:{alignItems:'center',justifyContent:'center',flex:1},buttonContainer:{width:'60%',alignItems:'center',justifyContent:'center',marginTop:30,},buttons:{backgroundColor:'#0782F9',padding:10,borderRadius:10,width:'100%',marginTop:5},inputContainer:{width:"80%"},input:{backgroundColor:'white',paddingHorizontal:15,paddingVertical:10,borderRadius:10,marginTop:5}})

App.js

import { NavigationContainer, NavigationRouteContext, useNavigation } from '@react-navigation/native';import { createNativeStackNavigator } from '@react-navigation/native-stack';import { StyleSheet, Text, View  ,Button} from 'react-native';import Createpost from './Components/Createpost';import Home from './Components/Home';import Login from './Components/Login';const Stack = createNativeStackNavigator()export default function App() {return (<NavigationContainer><Stack.Navigator><Stack.Screen name='Login' options={{headerTitleAlign:'center'}} component={Login}/><Stack.Screen name='Home' component={Home} options={({navigation})=>({title:'Home',headerTitleAlign:'center',headerTitleStyle:{color:'#120E43'},headerStyle:{backgroundColor:'#51E1ED',headerTitleAlign:'center'},headerRight:()=>(<Buttontitle='Logout'onPress={()=>navigation.navigate('Login')}/>),headerLeft:()=>(<Text></Text>)})}/><Stack.Screen name='Createpost' component={Createpost}/></Stack.Navigator></NavigationContainer>);}

Run -> expo start

Result :

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

--

--