How to deal with parent child components in Reactjs

How to deal with parent child components in Reactjs

Introduction 1.1. Web Components React is a component driven library, the idea is that we can create a component and reuse it over the entire application and each component has its own responsibilities which is been called as re-usability and...

Introduction 1.1. Web Components

React is a component driven library, the idea is that we can create a component and reuse it over the entire application and each component has its own responsibilities which is been called as re-usability and separation of concerns respectively. E.g button, textbox.

1.2 Virtual DOM

When we are working with really large applications and if we want to render or re-render thousands of DOM elements on getting data from server or from any other source it becomes hard for the browser to render and also takes time, so React uses a strategy called virtual DOM what it does is basically apply a diff algorithm on the DOM and if anything changes on the sub-tree structure it only updates the sub-tree instead of updating the entire tree.

1.3. Javascript and HTML

Because React is a component driven library and we are building component not just javascript library so here we are in need for something like a combination of javascript and HTML under a single roof so to make it easy something called JSX is used, to make it working React offering JSXTransformer.

Key things in React 2.1. Props

In simple if you want to pass any data to the component we have to use props E.g. value in button, onclick in button are better examples for the props (properties).

2.2. State

State holds all the information about the component and carries the state values to its children using props.

2.3. Life Cycle of components

Understanding life cycle of React is useful in building a better component, the render method is the most important and required specification method apart from that there are many other life cycle methods available which are invoked on their corresponding stages in React, here we will discuss only few things which are really important.

2.3.1 getInitialState

Called and return initial values of the state before anything happens on the component.

2.3.2 componentWillMount

Called before rendering the component and called only once in the entire life cycle of the component.

2.3.3 componentDidMount

Called after rendering the component only once in the entire life cycle of the component.

2.3.4 componentWillUpdate

Called before updating the component. This won’t be called on initial rendering, but on further props or state update.

2.3.5 ComponentWillReceiveProps

Called when a component receives props useful when dealing with parent and child components we will see in detail below

Coding Time (parent child relation) Here we are going to create a simple application (source code) for countdown timer which contains countdown timer as a parent component and child as label component. This is to give some idea about how parent and child component communicate each other rather than what we are building here.

For simplicity I am writing everything in same file

Include the react library and JSXTransformer first [code language=”html”]


Creating a Label component which acts as a child component in our example [code language=”html”] /**

  • Label component which just displays the given
  • text
  • / var Label = React.createClass({ propTypes: { prefixText: React.PropTypes.string, actualText: React.PropTypes.string }, // returns state data getInitialState: function() { return {actualText: ”, prefixText: ”, color:{color:this.getRandomColor()}}; }, getRandomColor: function() { var letters = ‘0123456789ABCDEF’.split(”); var color = ‘#’; for (var i = 0; i < 6; i++ ) { color += letters[Math.floor(Math.random() * 16)]; } return color; }, // called on receiving the props componentWillReceiveProps: function(nextprops) { this.props = nextprops; this.setState(this.props); this.setState({color: {color:this.getRandomColor()}}); }, render: function() { return (
    {this.state.prefixText} {this.state.actualText}
    ); } }); [/code]

What does Label component do?

The label component just receives the properties from its parent using the function componentWillReceiveProps and using the property we are updating the state value which is same as props and additionally we are having color state value which is owned by Label component itself.

[code language=”html”] componentWillReceiveProps: function(nextprops) { this.props = nextprops; this.setState(this.props); this.setState({color: {color:this.getRandomColor()}}); }, [/code] Creating a Parent component which is a countdown timer component in our example [code language=”html”] /**

  • Timer component which does timer functionalities and
  • render the child component
  • / var Timer = React.createClass({ propTypes: { time: React.PropTypes.number.isRequired }, componentDidMount: function() { var that = this; setInterval(function() { that.tick(that); }, 1000); }, getInitialState: function() { return {timedown: this.props.time, text: ‘your count down started’, prefix: ‘oh!’}; }, tick: function(current) { current.state.timedown -= 1000; if(current.state.timedown > -1) { switch (current.state.timedown) { case 0: current.state.text = “Your timer stopped”; current.state.prefix = “oh no”; break; case 1000: current.state.text = “Your timer going to stop in a minute”; current.state.prefix = “Make it fast”; break; case 2000: current.state.text = “You are very near”; current.state.prefix = “Hurry up!”; break; default: current.state.text = “there is only ” + this.state.minutes + ” minutes left”; current.state.prefix = “come on…”; break; } var seconds = Math.floor((current.state.timedown/1000) % 60); var minutes = Math.floor((current.state.timedown/1000) / 60); var hours = Math.floor((current.state.timedown/1000) / (60 * 60)); current.setState({hours: hours, minutes: minutes, seconds: seconds}); } }, render: function() { return (


    ); } }); [/code] What does Timer component do?

Tick function does all the countdown timer works for us which is not necessary atleast for now. We are rendering the label component (child component inside our parent component) as below and properties as actualText and prefixText which are updated on in setInterval function timer component

That’s it we are done with parent and child components, if you want further understanding please use the source code.

In next blog we will see how to create a React component using es6 and FLUX and with clean folder structure

Looking for ReactJS Development Company, your search ends here!

Be it a software developer, programmer, coder, or a consultant, CronJ has it all. CronJ has been a trustworthy company for startups, small companies, and large enterprises. Hire the web of experienced React developers for your esteemed project today. ReactJS Development Services

react software softwaredevelopment cronj

What is Geek Coin

What is GeekCash, Geek Token

Best Visual Studio Code Themes of 2021

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

How to Select and Hire the Best React JS and React Native Developers?

Hire React JS developer from Technoduce, we have a team of experienced and expert Angular JS developer. With our hire React JS developer, you have complete control over the technical resource throughout the development process.

React Native Development Company USA

CronJ Technologies is a next-generation global <a href="" rel="nofollow">technology</a> company that encourages startups to reimagine their industries for the digital age. Our tech-savvy...

Custom Software vs Off-the-shelf Software: How to select a better one for your business?

Custom Software or Off-the-shelf software, the question in mind for many business personnel. Read this blog to get help to make right decision that will benefit your business.

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? Also, we will see the react hooks example.