How to Create a Simple Contact Form in React Native with Firebase Realtime Database

React Native is getting more popular among developers concentrated in the hybrid apps. Building a native app for each platform is more complicated nowadays. This is the main reason for React Native’s huge rise. I already made some tutorials on React Native and you can see them under this article. Firebase is a Google managed service which provides a lot of services. Real-time Database is one of the popular services from them to store your data as no-SQL. In this blog, I am following a directory location for doing all my projects which is /var/www/ html. This is only a note for you to understand the upcoming steps in this article. Let us start.



FIREBASE

We are going to set up the firebase database first. Go to firebase console using the below link.

https://console.firebase.google.com/

Then click Add Project. This will show a form and fill it with your Project Name and Country. Now accept the terms and conditions and click Create Project button. You can see the details I gave from the below image.

Image is loading ...

 

Your firebase project is created. You will e directed to a page as below.

Image is loading ...

From the side menu, select Database. From there, you will get two database options such as Cloud Firestore and Realtime Database. Click an Create Database button from Realtime Database. Now it checks for the permission you wanted to give for the database. Select Start in Test Mode and click Enable. It is shown in the below image.

Image is loading ...

Now you will be directed to a page as below. Add a collection by entering a collection name as I did. I gave the collection name contactsIt’s just a simple step by clicking the input field on the right of the project ID, input your collection name and press Enter. Done.

Image is loading ...

 



REACT NATIVE

1. INSTALL AND SETUP REACT NATIVE

I already made a tutorial on installing and setting up of React Native. You can see it from the link below. But note that you have to change the project name AwesomeProject to ReactnativeContactForm (Step 9). Because in this tutorial, I am using that name. But as I told, It is not mandatory for you to follow my naming systems. You can choose your own. In that case, you have to use them in the upcoming steps too.

https://www.techomoro.com/how-to-install-and-setup-react-native-on-ubuntu-17-10

2. INSTALL NATIVEBASE

Nativebase is a node package which allows you to use some UI components for React Native. If you can build your UI components using Flexbox, or you are using any other packages to setup UI,  then this step is not mandatory for you.

npm install native-base --save
react-native link

3. EDIT APP.JS

The index.js file is executed first in React Native. As a default, App.js file is imported to the index. So The code inside App.js is executed. The rendered view you are seeing first time on your device is coming from this file. We are going to edit this.

First, import all components from their locations/ libraries. Some of the components I imported from native-base are also available in the react-native library. I imported them from native-base because they are pre-styled and it saves a lot of time.

import React, { Component } from 'react'
import { StyleSheet, TouchableOpacity, View, Alert } from 'react-native'
import { Container, Header, Title, Content, Text, Icon, Card, CardItem, Item, Body, Right, Button, Input, Form, Textarea, Left } from 'native-base'

Now add a class named App and export it.

export default class App extends Component {
}

Inside this class, define a constructor function and declare all the states we need to store our data. The states are null by default. isSubmitedis to store the submitted status of the form. Its value will be false as default.

constructor(props) {
  super(props);
  this.state = {
  name: null,
  mobile: null,
  email:null,
  msg: null,
  isSubmited: false, 
};
}

Now we need to add a function postContact() which posts the contact details we input using the form to the firebase database. The function postContact() contains some parameters. They are the submitted values from form and ref values of form input fields. In this function, first, we check if the message submitted from the form is null or not. If it is null, a warning alert is shown. If it’s not the form values are posted to the firebase database. In my case, the databaseUrl of my firebase is https://contact-form-db-133.firebaseio.com. You have to check your databaseUrl. It’s simple. Go to

https://console.firebase.google.com/

Then select your project and select Add project to your web app button. You can see your databseUrl there.

you have to add the collection_name.json that you already created as the extension of the databaseUrl to post the data.

postContact= (name, mobile, email, msg, nameClear, mobileClear, emailClear, msgClear) => {
  if(this.state.msg!=null){
   fetch('https://contact-form-db-133.firebaseio.com/contacts.json', {
   method:'POST',
   headers: {
   Accept:'application/json',
   'Content-Type':'application/json',
  },
   body:JSON.stringify({
    "name":name,
    "mobile":mobile,
    "email":email,
    "msg":msg,
    }),
   })
  .then((response) => response.json())
  .then((responseData) => {
    if(responseData.name !=null ){
    this.refs[nameClear].setNativeProps({text:''});
    this.refs[mobileClear].setNativeProps({text:''});
    this.refs[emailClear].setNativeProps({text:''});
    this.refs[msgClear].setNativeProps({text:''});
    this.setState({
    name:null,
    mobile:null,
    email:null,
    msg:null,
    isSubmited:true,
   })
 }
else{
  Alert.alert(
   'Oops !',
   'Something went wrong',[
    {text: 'OK', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},],
   { cancelable: false })
 }
})
.done();
}
else{
  Alert.alert(
   'Oops !',
   'Press SUBMIT button after entering your message',[
   {text: 'OK', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},],
   { cancelable: false })
   }
};
Now I am going to add a function _togglePostCard() which sets the state isSubmited to false. This function will be called after pressing the refresh button on the submitted form card.
_togglePostCard(){
  this.setState({
  isSubmited:false
 })
}
We need a render() function to display anything on the app screen. In this render(), we added a card. If the state isSubmited is true, we will display a CardItem with “Thank you” message and if isSubmitted is false, we will display a form to submit the details.
I am going to explain a little bit about the contact form.
  • On changing the text in each input field, the value is set to its corresponding states
  • A ref variable is with each input fields to clear the value in the input box field after submitting the form.
  • Keyboard type is added with each input.
  • On pressing the SUBMIT button, the input states and the ref variables will be passed with the postContact() function as function parameters. The recommended method is binding the postContect() function with the states. But here the states are simply passing as the function parameters.
  • posting the form data to firebase will return an object like { “name”: “id”}. We are using this to verify that the data is posted successfully on the firebase.
So the complete render() function will look like the below.
render() {
   return (
     <Container>
      <Header androidStatusBarColor="#1362af" style={{ backgroundColor: '#1976D2' }}>
      <Body style = {{ flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }}>
     <Title>CONTACT</Title>
      </Body>
      </Header>
     <Content>
      <Cardstyle={styles.postCard}>
{this.state.isSubmited ?
      <View>
      <CardItem>
       <Item>
         <Icon activename="ios-checkmark-circle" style={{fontSize:30, color:'#4CAF50', marginLeft:5, marginRight:10}}/>
         <Textstyle = {{flex:1}}>Thanks. We will get in touch with you as soon as possible</Text>
         </Item>
      </CardItem>
      <CardItem>
         <Left>
         </Left>
         <Body>
           <Touchable OpacitysuccessonPress={() =>this._togglePostCard()}>
               <Icon active name="refresh" style={{fontSize:50, color:'#64DD17', marginLeft:10}}/>
           </TouchableOpacity>
         </Body>
         <Right>
         </Right>
      </CardItem>
      </View>
:
      <View>
       <CardItem>
         <Item>
           <Inputplaceholder='Name' onChangeText={(name) =>this.setState({name})} ref={'nameClear'}/>
         </Item>
         </CardItem>
          <CardItem>
             <Item>
                  <Input placeholder='Mobile' onChangeText={(mobile) =>this.setState({mobile})} ref={'mobileClear'} keyboardType = {'phone-pad'}/>
            </Item>
       </CardItem>
       <CardItem>
             <Item>
                <Input placeholder='Email' onChangeText={(email) =>this.setState({email})} ref={'emailClear'} keyboardType = {'email-address'}/>
             </Item>
       </CardItem>
       <Form style = {{ marginLeft:20, marginRight:20 }}>
           <TextarearowSpan={5} borderedplaceholder="Type your message" onChangeText={(msg) =>this.setState({msg})} ref={'msgClear'}/>
       </Form>
      <CardItem>
       <Left>
      </Left>
      <Body>
        <Button successonPress={() =>this.postContact(this.state.name, this.state.mobile, this.state.email, this.state.msg, 'nameClear', 'mobileClear', 'emailClear', 'msgClear')}>
        <Text>SUBMIT</Text>
        </Button>
      </Body>
     <Right>
     </Right>
    </CardItem>
  </View>
  }
 </Card>
</Content>
</Container>
);
}

Now the contact form is set. Add some styles as shown below. This should be added outside the class we created.

const styles = StyleSheet.create({
  postCard: {
  marginLeft:25,
  marginRight:25,
  marginTop:20,
  marginBottom:20,
}
});

After you submit a contact form in React Native, the data will be stored as collections in Firebase realtime database. You can see them by a GET request to the URL below.

https://contact-form-db-133.firebaseio.com/contacts.json

Yes. This is the same URL you used to post the data.

NOTE: Your current permission on firebase database allows anyone to post and get data. So you need to change it later.

 

If you need a signed APK of your app, just follow the steps in the link below.

https://www.techomoro.com/how-to-generate-signed-apk-in-react-native



GITHUB

The complete project I created is uploaded in GitHub and you can always refer it.

REACT NATIVE
https://github.com/syamjayaraj/ReactnativeContactForm

Have a nice code !

9 thoughts on “How to Create a Simple Contact Form in React Native with Firebase Realtime Database

  1. hello, i try the same but it get this warning:
    undefined is not an object(evalating ‘_this3.set.Name’)

  2. Greetings, I was just visiting your site and filled out your contact form. The contact page on your site sends you these messages via email which is the reason you are reading my message right now right? This is the most important achievement with any type of advertising, making people actually READ your advertisement and this is exactly what you’re doing now! If you have something you would like to blast out to thousands of websites via their contact forms in the US or to any country worldwide let me know, I can even focus on particular niches and my prices are very reasonable. Write an email to: [email protected]

  3. Have you heard that contact form messages like these are in fact an effective method to get more visitors and sales for your website? How do we do this? Simple, we create an ad for you and we submit it to thousands contact pages on any kind of website you want. Do ads like these work well? By reading this now, you just proved that they do! What’s more, this won’t cost you much more than a cup of coffee a day! Interested in more details? send a reply here: [email protected]

  4. I think you misspelled the word “const” on your website. If you want to keep errors off of your site we’ve successfully used a tool like SpellPros.com in the past for our websites. A nice customer pointed out our mistakes so I’m just paying it forward :).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.