#100DaysOfCode : Building a React App contd…
Project (1 Hour): Learn how to add data persistence to the app using ReactFire and Firebase which provides a realtime JSON database for storing and syncing your app’s data. Why firebase? Firebase + Batch (for push notification) has been a popular choice in the developer community after Parse was discontinued. Build notes component that shows data seeded in firebase.
All the code for this project can be found on my github
Step 1: Install ReactFire and Firebase
npm install --save reactfire firebase
Also create a firebase account, you can use this JSON file to seed data.
Step 2: Setup Firebase and upgrade Profile component
Require all packages that are needed such as reactfire and firebase as specified in the Profile component below.
Add “componentDidMount” lifecycle event that is triggered when component mounts on the view. In this event, create new instance of firebase and set it up to point to your newly created firebase URL.
Note we add a keyword mixin when we create react component which appends reactfire functionality to “this” instance. The “bindAsArray()” method is available due to reactfire mixin, can now be triggered on “this” instance. “bindAsArray” takes two arguments.
First is the data from firebase that you want to bind to the view. In our case, we go one level deep on root firebase object to retrieve notes on a specified “this.props.params.username” from our request URL.
Second is the property on state that your want to bind your firebase data to, which in our use case in “notes”.
componentWillUnmount event is finally added to unbind reactfire and remove listener on it when component unmounts.
Step 3: Notes List component
Create NotesList.js which will contain a bootstapped unordered list where each list item is populated from an array passed to the component. In our example we use the map “this.props.notes.map” that allows you to iterate over all elements in the array, modify it with callback function and spits out each element from modified array.
In our example, as per the above code, we take each note value and create a bootstrapped list item which then gets rendered within unordered list.
Step 4: Transpile and run
Finally run webpack and open your index page with “/profile/test” appended to it in browser and your component should look like this output image with notes listed out .
Day 3 of #100DaysOfCode DONE
If you enjoyed this, please click 👏 so that others can enjoy it as well. Follow me on Twitter @HariniLabs to get the latest updates or just to say Hi :)