Challenge 3 - Getting started with ReactJS - Understanding Props and States

Register
Submit a solution
The challenge is finished.

Challenge Overview

Abstract

We have launched series of fun challenges to help introduce you to ReactJS. This is third challenge of the series. You will learn about props, states, and how to pass data between two components in this fun challenge using ReactJS and JSX.
 

Important Note:
This is a fun challenge. No prize money will be awarded for completing this challenge successfully.

 

Challenge Details

What is ReactJS?

React is an open-source JavaScript library to build user interfaces. In other words it’s a View of MVC which helps you to render HTML.


Requirements for this challenge

We highly recommend you to read past two challenges (First Challenge, Second Challenge)of the series. In this challenge you will be creating 1 button that reads “Change value of PI”. The default value will be PI and every time the button is clicked, the value of PI will be added to it.  By the end of this tutorial you will learn about props, states, and how to manage data between two components as well as accessing it.


Step1: Understanding Props

  • Props is an abbreviation for properties.
  • You can think of props as a function’s argument which is being passed to a function to perform a certain operation, similarly props act as an argument to a component.
  • Props cannot change its value during the lifecycle of the component.
  • Props are passed from a parent component to child component.
 

Step 2: Implementing Props

  • Create a new component in your project which you have created in the second challenge.
  • Import the the newly created component in ./Main.js file.
  • Make changes in the JSX code by passing the container you have passed to import the new component. The code below will give you insight:
 

NewC.js

 

import React from "react";

export class NewC extends React.Component{

  render()

  {

      return(

          <div>

              <h2>In a child Component</h2>

          </div>

      );

  }

}

    

  • Pass the new component in ./Main.js’s JSX code and props.  

                      

import React from 'react';

import { render } from 'react-dom';

Import {NewC} from './NewC'

class Hello extends React.Component {

             render() {

                const pi = 3.14;

                             const weekdays = ['Mon','Tue','Wed','Thus','Fri'];

 

//JSX code in return function     

              return (

                   <div>

                      <h1>Hello World!</h1>

                  <P className="Con"> The value of pi is: {pi}</p>

                  <ul>

                    {weekdays.map( (day, i) => <li key={i}>{day}</li>)}

                  </ul>

                <NewC Name = {"TOPCODER"}/>

                       </div>

                      );

     }

}

render(<Hello/>, document.getElementById('app'));

 
  • The new component NewC will get transpiled and the content mentioned in the new component will be displayed in a browser.
  • We have also passed props along with a new component in JSX. The parent component will pass the Props (Name = {“TOPCODER”}) to the child component (NewC).
  • We can access props by using props keyword and by the "name" of the props defined in the parent component. So in our scenario we will access the prop in the following way:  
 

<div>

  <h2>In a child Component</h2>

  <h4> Prop passed from Parent component is {this.props.Name}</h4>

</div>

 
  • Also, you must always define the Proptype. You can think of Proptypes as a data validator that can be used to make sure the data we receive is valid. In this example, you are using PropTypes.string. In the case that you receive an invalid value for a prop, a warning will be shown in the JavaScript console.It can be defined at the end of the component in which we are accessing prop. In our code we will define propType in NewC.

        

NewC.PropTypes = { Name: React.PropTypes.string};

 

Step 3: Understanding State

  • Unlike props, State’s values can be changed with the help of a function.
  • State enables us to trigger re-rendering of the component.
  • State's value should be initialized by defining a constructor.
  • State acts as an instance of the component and get updated in the DOM on initialization.
 

Step 4: Implement State

  • State is created in component by declaring a constructor as shown below. The constructor will help us to initialize the defined state and thereby update the DOM.
 

constructor() {

      super();

      this.state = {Handle: "MyHandle"};

}
 

  • Handle is the state name and MyHandle is the value assigned to the state Handle
  • Props can also be passed to the constructor if we want to manipulate/use prop’s value in the app.
 

    constructor(props)

{

              super();

              this.state = {DT: props.pi };

            }

 

Step 5: Accessing State’s value

  • Value of state can be accessed by this keyword.
        {this.state.stateName}

  • Let’s define state in the code above and access it with an h2 tag
 

import React from 'react';

import { render } from 'react-dom';

Import {NewC} from './NewC'

class Hello extends React.Component {

//This how we define the state in a component.

constructor() {

  super();

  this.state = {Handle: "Your TC Handle"};

}

  render() {

  const pi = Math.PI;

  const weekdays = ["Mon","Tue","Wed","Thus","Fri"];

  const clock = new Date();

      return (

          <div>

              <h1>Hello World!</h1>

 

         <h2>My topcoder handle is {this.state.Handle}</h2>

 

              <a className = "try">The value of pi is:- {pi}

                <br/><br/>Current time is:- {clock.toString()} </a>

                              <ul> WeekDays

                 {weekdays.map( (day,i) => <li key = {i}>{day}</li>)}

               </ul>

              <NewC Name = {"TOPCODER"}/>

          </div>

      );

  }

}

render(<Hello/>, document.getElementById('app'));

 

That’s all you need to know in order to achieve the objective of this challenge. It’s time to change the value of PI on a button click. Let's get started
 

Step 1: Pass value of PI to child component

We need to pass the value of PI from parent component to child component i.e. from Main.JS to NewC. Let’s add PI as a prop to the child component.

..
...

<NewC Name = {"TOPCODER"} pi = {pi}/>
 

The pi in curly braces {pi} has already been defined as a const and been assigned the value of pi in this component(Main.js -> Parent Component).
 


Step 2: Access value of PI in child component

Let’s access the value of PI just the way we had accessed the value of the name above.
 

.
..
...

<h4> Name passed from Parent component is {this.props.Name}</h4>

<h3> Value of PI is {this.props.pi}</h3>

</div>

   );

}

}

NewC.PropTypes = { Name: React.PropTypes.string,

pi: React.PropTypes.number};

 

Step 3: Create a button and an event handler

As you need to add the value of PI to it’s own value, you need to create a button and a function to handle the action to be performed when the button is clicked.
 

//function to handle button click event

changePIvalue()

{

 

}

render()

{

.
.

<h4> Name passed from Parent component is {this.props.Name}</h4>

<h3> Value of PI is {this.props.pi}</h3>

<button onClick={()=> this.changePIvalue()}>Change pi value</button>

        </div>

   );

}

}

NewC.PropTypes = { Name: React.PropTypes.string,

pi: React.PropTypes.number};

 

Step 4: Define state

We will be passing props to the state constructor as we will be using the value of PI passed from the parent component(Main.js) to the child component(NewC.js)

 

constructor(props) {

  super();

  this.state = {PIValue: props.pi, count:1 };

}

changePIvalue()

{

..

.

.

The state “count” has been defined to keep a track on the number of times the “changePIvalue()” function has been called.

 

Step 5: Implement function “changePIvalue()”

We will set the value of PIValue in a way that it would hold the addition of pi value to the existing value of PIValue(i.e. 3.14 + 3.14 = 6.28). We will use props.pi value to return the addition of pi.

 

changePIvalue()

{

this.setState({

PIValue:this.state.PIValue + this.props.pi ,

count:this.state.count+1});

}

The above function will be called every time a user clicks the button. In order to keep track of how many times the function has been called we will make use of the state “count”.

Step 6 : Access change value of state
 

Let’s make use of the value of states which we have manipulated using function changePIvalue().
 

<h4> Name passed from Parent component is {this.props.Name}</h4>

<h3> Value of {this.state.count} PI is {this.state.PIValue}</h3>
 

{this.state.count} will indicate how many times the button was clicked. {this.state.PIValue} will indicate the respective addition of PI value.




Your new component NewC will look like

import React from 'react';

export class NewC extends React.Component

   {

   constructor(props) {

        super();

        this.state = {PIValue: props.pi, count:1

        };

   }

   changePIvalue()

   {

   this.setState({

   PIValue:this.state.PIValue + this.props.pi ,

   count:this.state.count+1});

   }

    render()

      {

            return(

              <div>

           <h2>In a child Component</h2>

                <h4> Name passed from Parent component is {this.props.Name}</h4>

                <h3> Value of {this.state.count} PI is {this.state.PIValue}</h3>

                <button onClick={()=> this.changePIvalue()}>Change pi value</button>

              </div>

          );

      }

   }

   NewC.PropTypes = { Name: React.PropTypes.string,

   pi: React.PropTypes.number};

 

Step 7: Run your application

Run your application with the command “npm start”
 

Just to recap this fun challenge, I would like to highlight the following points

  • We have learned about props and states
  • We have learned how to implement event handler
  • We have learned how to manage data between two components
Should you have any questions, feel free to post it in the challenge forum.



Important Note:
This is a fun challenge. No prize money will be awarded for completing this challenge successfully.



Final Submission Guidelines

Upload screenshot of the browser window with output. Also, upload screenshot of the developer console.

Note:- The developer console should not have any errors/warnings.


Screenshot for expected output is attached.

Important Note:
This is a fun challenge. No prize money will be awarded for completing this challenge successfully.

Review style

Final Review

Community Review Board

Approval

User Sign-Off

Challenge links

ID: 30060532