07 Jun Learn Basics of React.js in 11 Minutes

If you are new to React.js this tutorial will give you introduction to all basic concepts in react.

What and Why?

This article is not going to cover details of what and why? Although you should be knowing by now that React is a JavaScript library aimed to create user interfaces and used extensively by social networking platforms like Facebook and Instagram to name a few.. It is fast, responsive, modular, we can create reusable files. It is scalable and flexible. Many more advantages but we will jump right into some basic concepts.

What is Virtual DOM?

DOM(Document Object Model) is the UI components, like elements, attributes.

Virtual DOM is node tree listing of components, which is light weight in memory representation of real DOM.

The render() method in react creates it.

Each time the underlying data changes, new virtual DOM is created, comparing differences between previous virtual DOM and only the changes are updated in real DOM.

So, the special thing about ReactDOM.render() is that it only updates DOM elements that have changed. Aha!!!

JavaScript extension, JSX is not valid JavaScript that browsers can read. It’s a JavaScript file that contains JSX code, very similar to HTML and the file have to be complied before it reaches web browser, with JSX complier that translates the JSX into JavaScript.

JXS element are treated as JavaScript expression, they can be saved as variable, passed to function or stored in an object or array.

Each JSX expression must have exactly one outermost element. Usually wrap the JSX expression in a <div></div>.

Rendering JSX element means to make it appear on screen. We render JSX expression like this:

In HTML, it’s common to use class as an attribute name but in JSX we cannot use the word class. We have to use className instead. Coz class is reserved word in javaScript and JSX is converted to javaScript.

In HTML its optional to include forward slash for self-closing tags like br, img, input, etc but not in JSX.

Curly braces are markers that signal the beginning and end of a JavaScript:

We can pass props from component to component. Rendering is the only way for a component to pass props to another component. Here is an example:

1

import React from‘react’;

1

export classGreeting extendsReact.Component{

1

render(){

1

return&lt;h1&gt;Mynameis{this.props.name}!&lt;/h1&gt;;

1

}}

Lets import Greeting:

1

import React from‘react’;

1

import ReactDOM from‘react-dom’;

1

import{Greeting}from‘./Greeting.js’;

1

classApp extendsReact.Component{

1

render(){

1

return(

1

&lt;div&gt;&lt;Greeting name=”bahubali”/&gt;&lt;/div&gt;

1

);

1

}}

1

ReactDOM.render(App/&gt;,document.getElementById(‘app’));

Passing event handler as a prop. Here is an example:

1

import React from‘react’;

1

export classButton extendsReact.Component{

1

render(){

1

return(

1

&lt;button onClick={this.props.talk}&gt;me!&lt;/button&gt;

1

);

1

}}

Lets import Button class:

1

import React from‘react’;

1

import ReactDOM from‘react-dom’;

1

import{Button}from‘./Button’;

1

talk(){

1

alert(‘yaaayy!!!’);

1

}

1

classApp extendsReact.Component{

1

render(){

1

return&lt;Button talk={this.talk}/&gt;;

1

}}

1

ReactDOM.render(Talker/&gt;,document.getElementById(‘app’));

Every component’s props object has a property named children, this.props.children will that returns everything in between a component’s opening and closing JSX tags.

1

import React from‘react’;

1

classBigButton extendsReact.Component{

1

render(){

1

console.log(this.props.children);

1

return&lt;button&gt;THISISBIG BUTTON HERE&lt;/button&gt;;

1

}}

1

// Example 1

1

&lt;BigButton&gt;

1

Iamachildof BigButton.

1

&lt;/BigButton&gt;

If nobody passes any text to component, then component display will be blank. It would be better if component could display a default message instead. That’s where defaultProps comes into picture.

1

classExample extendsReact.Component{

1

render(){

1

return&lt;h1&gt;{this.props.text}&lt;/h1&gt;;

1

}}

1

Example.defaultProps={text:‘yo’};

What is a State?

A React component can access dynamic information in two ways: props and state.

Unlike props, a component’s state is not passed in from the outside. A component decides its own state.

To make a component have state, give the component a state property. This property should be declared inside of a constructor method, like this:

1

classExample extendsReact.Component{

1

constructor(props){

1

super(props);

1

this.state={mood:‘decent’};

1

}

1

render(){

1

return&lt;div&gt;&lt;/div&gt;;

1

}}

this.state should be equal to an object.

To read a component’s state, use the expression this.state.name-of-property.

The most common way to call this.setState() is to call a custom function that wraps a this.setState(). As shown in below example:

1

classExample extendsReact.Component{

1

constructor(props){

1

super(props);

1

this.pancake=this.pancake.bind(this);

1

}

1

pancake(){

1

this.setState({breakfast:‘panake’});

1

}}

There is a stateful component, and a stateless component. “Stateful” describes any component that has a state property; “Stateless” describes any component that does not. Pretty simple, eh!

Example of passing component from stateful component to stateless component:

1

import React from‘react’;

1

import ReactDOM from‘react-dom’;

1

import{Child}from‘./Child’

1

classParentextendsReact.Component{

1

constructor(props){

1

super(props);

1

this.state={name:‘Frarthur’}

1

}

1

render(){

1

return&lt;Childname={this.state.name}/&gt;;

1

}}

1

ReactDOM.render(&lt;Parent/&gt;,document.getElementById(‘app’));

Lets import to a stateless component:

1

import React from‘react’;

1

export classChildextendsReact.Component{

1

render(){

1

return&lt;h1&gt;Hey,mynameis{this.props.name}!&lt;/h1&gt;;

1

}}

Stateless components updating their parents state is a React pattern that you’ll see alot.

A component can change its state by calling this.setState() but a component should never update this.props. A React component should use props to store information that can be changed, but can only be changed by a different component. A React component should use state to store information that the component itself can change.

Child component can update the parent’s state as shown in below example, by passing a function down to child that can change parent’s state. Please note: binding at constructor level to make sure the method always refers to the instance of parent.

1

import React from‘react’;

1

constructor(props){

1

super(props);

1

this.handleChange=this.handleChange.bind(this);

1

}

1

2

3

4

// When a user selects a new dropdown item, it will invoke

// changeName, but it won’t pass the correct argument! Instead of

// passing a new name, it will pass an event object, as all event

// listeners do. This is a common problem when passing down an event // handler in React! The solution is to define another function that // can extract the name from the event object.

1

handleChange(e){

1

constname=e.target.value;

1

this.props.onChange(name);

1

}

1

export classChildextendsReact.Component{

1

render(){

1

return(

1

&lt;div&gt;

1

&lt;h1&gt;Heymynameis{this.props.name}!h1&gt;

1

&lt;select id=”great-names”onChange={thi.handleChange}&gt;

1

&lt;option value=”Frarthur”&gt;Amazonoption&gt;

1

&lt;option value=”Gromulus”&gt;Google&lt;/option&gt;

1

&lt;/div&gt;

1

);

1

}}

When passing down event handler it will pass event object, so we need another function in child to extract the name from event object.

An uncontrolled component is a component that maintains its own internal state. A controlled component is a component that does not maintain any internal state. Since a controlled component has no state, it must be controlled by someone else.

We all know forms from html. In react, for certain cases, it’s fine to have a form that is really just an input field. This is because, unlike in the traditional form paradigm, in React you re-send your form on every single character change. That removes the need to ever “submit” anything.

What are Lifecycle methods?

Lifecycle methods are methods that get called at certain moments in a react component’s life.

There are three mounting lifecycle methods, when a component mounts, it automatically calls these three methods, in order:

componentWillMount: When a component renders for the first time only, componentWillMount gets called right before render.

render: We talked about it all along.

componentDidMount: When a component renders for the first time, componentDidMount gets called right after the HTML from render has finished loading.

If your React app uses AJAX to fetch initial data from an API, then componentDidMount is the place to make that AJAX call. It is a good place to connect a React app to external applications, such as web APIs or JavaScript frameworks or to set timers using setTimeout or setInterval.

There are five updating lifecycle methods, which is called in this order whenever a component instance is updated:

componentWillReceiveProps: When a component instance updates, componentWillReceiveProps gets called before the rendering only if the component will receive props.

shouldComponentUpdate: shouldComponentUpdate automatically receives two arguments: nextProps and nextState. It’s typical to compare nextProps and nextState to the current this.props and this.state. If shouldComponentUpdate returns true, then nothing noticeable happens. But if shouldComponentUpdate returns false, then the component will not update.

componentWillUpdate: componentWillUpdate gets called in between shouldComponentUpdate and render.It receives two arguments: nextProps and nextState. We cannot call this.setState from componentWillUpdate. Its main purpose is to interact with things outside like checking the window size or interacting with an API.

render: We talked about it all along.

componentDidUpdate: componentDidUpdate automatically gets passed two arguments: prevProps and prevState. prevProps and prevState are references to the component’s props and state before the current updating period began. You can compare them to the current props and state.

Finally, there is only one unmounting lifecycle method:

componentWillUnmount: It gets called right before a component is removed from the DOM.

That’s it. We are done, go get your amazing React applications. Thank you for reading.

You’re born alone and you die alone and this world just drops a bunch of rules on top of you to make you forget those facts. But I never forget. I’m living like there’s no tomorrow, because there isn’t one.