Lets React More !

Umair Khan
Sep 9, 2018 · 5 min read

Ok so time for some more Reactions.. In the previous blog we saw how we could create awesome clock using React.js

In this blog we shall see how components can be created and reused. I will also be using Bootstrap css. However Bootstrap is out of the scope of this blog
We shall also enjoy how data can be passed from the parent to the child component.

Lets get started. First things first. Include Bootstrap… How? Include the stylesheet of Bootstrap
<link href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel=”stylesheet”> in the index.html

Other way would be to install as a node package which I am not doing right now… Who cares .. !

Now we shall be building the a simple application that allows to display a simple form multiple times. This is the final app we would have, when we finish:

What we are building !

Lets begin..

Make WorkInfoForm component

This is basically the form we shall be dispalying multiple times. I have made it as a separate comppnent to allow reusability
Inside your src folder, then components create new folder work-info-form

Here throw in the following code:

import React, { Component } from ‘react’;

class WorkInfoForm extends Component {

emailInputId = “”;
passwordInputId = “”;

render() {

return (

<div className=”Form-container”>
<div className=”Controls-container”>
<label htmlFor=”email”>Email address</label>
<input onChange={this.onEmailChanged} type=”email” className=”form-control” id={this.emailInputId} placeholder=”Enter email” />
</div>
<div className=”Controls-container”>
<label htmlFor=”password”>Password</label>
<input onChange={this.onPasswordChanged} type=”password” className=”form-control” id={this.passwordInputId} placeholder=”Password” />
</div>

</div>
)
}
}


export default WorkInfoForm;


A lot of stuff is going on here. so for the time being just look at the render function. this function is basically responsible to display the form on the screen as you can see only two items: an input to enter email address and an input for the password has been made.

Working on app.js

Ok so how do we display this form. Open up the app.js file and write the followign code inside the app class:

constructor(props) {
super(props);
this.state = {
“NoOfForms”: 0,
“FormData”: []
};
}

As you can see we are setting the state for the App component of the app. NoOfForms is not utilzied anywhere though. FormData is basically the array that is going to hold multiple forms data.

Now write two more function inside the App class. the addForm is responsible to add new form and resetForm removes all the forms. The arrow notation binds the functions to the class, otherwise they would not be called in the render function.

addForm = () => {

var forms = this.state.FormData;
forms.push({});
this.setState({ FormData: forms });

}

resetForm = () => {
this.setState({ FormData: [] })

}

Its clear that resetForm removes all the objects from the array. In the render function we shall be doing the following:

var forms = [];

for (var i = 0; i < this.state.FormData.length; i++) {

var keyForForm = i;
var dataToPass = this.state.FormData[i];

forms.push(
<WorkInfoForm key={keyForForm} data={dataToPass} identifier = {keyForForm} />
);
}

First we create JSX element to disply forms. WorkInfoForm is basically calls the component to render. key is required to uniquely identify the item in the loop. data is used to hold the data. As you can see we are passing a single object from the state object to hold data, accessed by the index in the line: var dataToPass = this.state.FormData[i];

Putting things into place

In the render method inside the return statement, enter the following lines:

<button type=”button” className=”Button-margin btn btn-default” aria-label=”Left Align” onClick={this.addForm}>

<span className=”glyphicon glyphicon-plus” aria-hidden=”true”></span> Click to add form

</button>

{

this.state.FormData.length > 0 && <button type=”button” className=”Button-margin btn btn- default” aria-label=”Left Align” onClick={this.resetForm}>

<span className=” glyphicon glyphicon-remove” aria-hidden=”true”></span>

Remove all forms

</button>

}

Its quite simple. The first button is basically used to add new form. We bind the onClick attribute to this.addForm. The second button is only added when at least one form has been added. Here we allow removing all the forms. this.resetForm performs this for us.

Now below these we enter the following code:

<div> {forms}</div>
{ this.state.FormData.length > 0 && <button type=”button” className=”btn btn-primary” onClick={this.submitPressed}>Submit</button>}

{form} is basically JSX syntax and it shall render the forms for us. Below this we add the Submit button to access the values. Its wired to this.submitPressed.

Wrap things up

How is the data bound to the App component when we are entering it inside the WorkInfoForm component. The answer is we have passed the variable as reference. Now each time the email address and password as changed they are stored in the holder variable we had passed using the following implementation:

onEmailChanged = () => {

this.props.data.Email = document.getElementById(this.emailInputId).value;

}

onPasswordChanged = () => {

this.props.data.Password = document.getElementById(this.passwordInputId).value;

}

These methods are wired to the onChange of Email input and password input. Now here is a catch… We are accessing the element by the id. The problem is if we hardcoded the element’s id we would not be able to access all the controls since id should be unique. The work around is to create ids. its actually quite simple. In the constructor of the WorkInfoForm we put these two lines:

this.emailInputId = “Email-” + props.identifier;
this.passwordInputId = “Password-” + props.identifier;

Now this identifier is always unique so IDs are unique for each form.


So now when things are all looking good… When we hit the Submit button following code is executed. This function is defined and bound to App component.

submitPressed = () => {

var string = “”;
for (var i = 0; i < this.state.FormData.length; i++) {
string += “Form: “ + (i +1) + “ Email Address: “ + this.state.FormData[i].Email + “ Password: “ + this.state.FormData[i].Password + “\n”;
}

alert(string);
}

As you can see we iterate over the state’s FormData array access the elements and generate the string.
A better way would be to display the data on either separate page or paragraph. But I am being too lazy and my tea is also over so I am just displaying the alert.

The complete code for this can be found on github: https://github.com/umairk83/React-Magic/tree/master/lets-react-more

(This blog was originally published at prahauk.blogspot.com)

Umair Khan

Written by

Just a humble being who is passionate about Software Development, loves Data Science, finds pleasure in Psychology & discovers world in music !

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade