The Ref attribute

React provides ref non-DOM attributes to access the component. The ref attribute can be a callback function, and it will execute immediately after the component is mounted. So we will attach the ref attribute in our form element to fetch the values.

Let's take a quick look at our component after adding the ref attribute:

<div>
<form ref = "form" onSubmit = {this.handleSubmitEvent}>
<div className = "form-group">
<label htmlFor= "email"> Email <span style = {style} > * </span></label>
<input type = "text" id = "email" className = "form-control" placeholder = "Enter your email address" required ref = "email" />
</div>
<div className = "form-group">
<label htmlFor = "issueType"> Issue Type <span style = {style}> * </span></label>
<select className = "form-control" id = "issueType" required ref = "issueType">
<option value = "" > -- -- - Select-- -- </option>
<option value = "Access Related Issue"> Access Related
Issue
</option>
<option value = "Email Related Issues"> Email Related
Issues
</option>
<option value = "Hardware Request"> Hardware Request </option>
<option value = "Health & Safety"> Health & Safety </option>
<option value = "Network" > Network < /option>
<option value = "Intranet"> Intranet </option>
<option value = "Other"> Other </option>
</select>
</div>
<div className = "form-group">
<label htmlFor = "department"> Assign Department <span style = {style} > * </span></label>
<select className = "form-control" id = "department" required ref = "department">
<option value = ""> -- -- - Select-- -- </option>
<option value = "Admin"> Admin </option>
<option value = "HR"> HR </option>
<option value = "IT"> IT </option>
<option value = "Development"> Development </option>
</select>
</div>
<div className = "form-group">
<label htmlFor = "comments"> Comments <span style = {style
} > * </span></label>
( <span id = "maxlength"> 200 </span> characters max) <textarea className = "form-control" rows = "3" id = "comments" required ref = "comment"> </textarea>
</div>
<div className = "btn-group"><button type = "submit" className = "btn btn-primary"> Submit </button> <button type = "reset" className = "btn btn-default"> cancel </button> </div>
</form>
</div>

Now, let's open the browser and see how our component looks:

Firebase is working perfectly in our application as you can see the message displayed at the bottom of title "Hello world! This is My First JavaScript Firebase App"; it's coming from Firebase Realtime Database

Also, in the console, you can see the values when we submit the form.

Now we need to save those value into the database:

//React form data object
var data = {
date: Date(),
email:this.refs.email.value.trim(),
issueType:this.refs.issueType.value.trim(),
department:this.refs.department.value.trim(),
comments:this.refs.comment.value.trim()
}

We do this to Write the Form data object to Firebase Realtime Database; firebase.database.Reference is an asynchronous listener to retrieve the data from Firebase. This listener will be triggered once on the initial state of that and when data gets changed.

We can Read and Write the data from Firebase Database if we have access for that, because, by default, the database is restricted and no one can access it without setting up the authentication.

firebaseDb.ref().child('helpdesk').child('tickets').push(data);

In the preceding code, we used the push() method to save the data into the Firebase Database. It generates a unique key every time a new child is added to the specified Firebase reference. We can also use the set() method to save the data for specified reference; it will replace the existing data at that node path:

firebaseDb.ref().child('helpdesk').child('tickets').set(data);

To Retrieve the update results when data is added, we need to attach the listener using the on() method, or in any case, if we want to detach the listener on the specific node, then we can do that by calling the off() method:

 firebaseDb.ref().on('child_added', function(snapshot) {
var data = snapshot.val();
snapshot.forEach(function(childSnap) {
console.log(childSnap.val());
this.refs.form.reset();
console.log("Ticket submitted successfully");
});
});

However, if we want to read them once without listening to the changes, we can use the once() method:

 firebaseDb.ref().once('value').then(function(snapshot){
});

This is useful when we don't expect any changes in the data or any active listening. For example, loading the user profile data on the initial load when it gets successfully authenticated in our app.

To update the data, we have the update() method and for deleting, we just need to call the delete() method at the location of that data.

Both the update() and set() methods return a Promise, so we can use that to know when the write is committed to the database.

Now, let's submit the form and see the output in the browser console:

That looks great; now, let's take a look our Firebase database:

We are able to see the data that we have submitted from the ReactJS form.

Now we'll display this data in a table format; for this, we need to create another React component and set the initial state of our component:

constructor(){
super();
this.state = {
tickets:[]
}
}

Now, using the componentDidMount() method, we will call the database by ref(), iterate the object, and set the state of the component with this.setState():

componentDidMount() {
var itemsRef = firebaseDb.ref('/helpdesk/tickets');
console.log(itemsRef);
itemsRef.on('value', (snapshot) => {
let tickets = snapshot.val();
console.log(tickets);
let newState = [];
for (let ticket in tickets) {
newState.push({
id:tickets[ticket],
email:tickets[ticket].email,
issueType:tickets[ticket].issueType,
department:tickets[ticket].department,
comments:tickets[ticket].comments,
date:tickets[ticket].date
});
}
this.setState({
tickets: newState
});
});
},

Now we will iterate the state of tickets in a table inside the render method:

render() {
return (<table className="table">
<thead>
<tr>
<th>Email</th>
<th>Issue Type</th>
<th>Department</th>
<th>Comments</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{
this.state.tickets.map((ticket) =>
{ return (
<tr key={ticket.id}>
<td>{ticket.email}</td>
<td>{ticket.issueType}</td>
<td>{ticket.department}</td>
<td>{ticket.comments}</td>
<td>{ticket.date}</td>
</tr> )})
}
</tbody>
</table>
)}

Now, the user can view the tickets' list on Realtime whenever a new ticket is added to the database:

Here's the markup of our HTML page: viewTickets.html:

 <div class="col-lg-10">
<h2>View Tickets</h2>
<hr>
<div id="table" class="table-responsive">
<!-- React Component will render here -->
</div>
</div>
</div>
</div>

This is the list of tickets added in Firebase Realtime Database:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset