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.ref.child(this.props.params.username).child(this.state.notes.ength).set(newNote)
}

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

<Notes
username={this.props.params.username}
notes={this.state.notes}
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
this.props.addNote(newNote)
}

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