Day 4: Validating and Managing State of React Components

#100DaysOfCode : Building a React App contd…

Project (1 Hour): Continue building on the app by adding notes taking component that syncs realtime to firebase. Trigger events from root to manage state along with validation of each component.

All the code for this project can be found on my github

Step 1: Validation using PropTypes

Specify properties that are required/not and their datatype for each component.

<Repos username={this.props.params.username} repos={this.state.repos}/>propTypes: {
username: React.PropTypes.string.isRequired,
repos: React.PropTypes.array.isRequired

Here, if we use “Repos” without say username it will now throw error to console. Add similar validation to all components.

Step 2: Managing component state

In React, state is managed at the top component level which gets passed on to the child. So for our usecase, to add note from a text box to firebase at the notes component level, we need to add a method at the root level component which in our case is Profile.js.

handleAddNote: function(newNote){

This method to add a “newNote” to the child on a username is then passed as a prop to the Notes component.

addNote={this.handleAddNote} />

Don’t forget to add it to PropTypes for validation in Notes.js

addNote: React.PropTypes.func.isRequired

Step 3: Add Note Component

Finally create a simple component with a text box and button, that lets you add notes to your firebase datastore.

onClick event on the button here will trigger “handleSubmit” which gets the managed function state “addNote” passed down to it from Profile -> Notes -> AddNote

handleSubmit: function(){
var newNote = this.note.value;
this.note.value = ‘’; //Empty textbox

Now running webpack and launching the profile should let you add notes that are synced realtime.

Day 4 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 :)

PS: I curate a bi-weekly #WomenInTech newsletter for a dose of inspiration from the world of tech and yes men can signup too! Get it here :)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store