Skip to main content

Featured

Java Interview Questions for Senior Full Stack Developer

Please like our page to get latest updates from only full stack

React Part 3 - Components state and props in React

What we have learned so far?

Part 1 - Hello Word in React?
https://onlyfullstack.blogspot.com/2019/11/create-reactjs-app-hello-world.html

Part 2 - JSX in React
https://onlyfullstack.blogspot.com/2019/11/jsx-in-react.html

Components in React

Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
When creating a React component, the component's name must start with an upper case letter.

The component has to extend the React.Component, this statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.
The component also requires a render() method, this method returns HTML.

Lets take an example and convert it into reusable React Component.
<div>
  <h1>Hello Only Fullstack</h1>
  <div>
    <h3 className="notification">
      You have 5 new notifications
    </h3>
    <h4 className="notification-component">
      I am coming from Notification Component
    </h4>
  </div>
  <p>Start editing to see some magic happen :)</p>
</div>

Output - 

Lets split above code into reusable components.
Please follow below url or below editor to see the react components.
Components without state and prop example


So we have divided the the HTML into reusable components. Lets see what we did?
We have splitter the components and highlighted the area with their component name.


How to create a new component in React?

We need to extend our component with React.Component class to get the React capability like state, props etc. We need to override the render() method of Rect.Component which will return the HTML of that component.

import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

export default class Notification extends Component {
  render() {
    
    return (
        <div>
          <h3 className="notification">
            You have 5 new notifications
          </h3>
          <h4 className="notification-component">
            I am coming from Notification Component
          </h4>
        </div>
      );
  }
}

It's simple. We splinted the HTML into components and now we will see how the components and have their own states.
Refer below link for API documentation -
https://reactjs.org/docs/react-component.html

You can create component with ES6 syntax but its hard to write down. Refer below URL to know more : https://reactjs.org/docs/react-without-es6.html

Components state in React

React components has a built-in state object.
The state object is where you store property values that belongs to the component.
When the state object changes, the component re-renders.

Lets have some state for Notification component. In OOP terms, state is nothing but an instance variables of a class.

We need to give some default values to the state variables. We can define the state object by defining it inn the components contractor and then we can use this state variable by this.state.propertyName.

Suppose you want to show the list of students coming from a rest api then we will call the rest api in constructor or in react hook(we will look into this later) to load the students and then assign this list of students to the state object to use it across the React component.
constructor() {
    this.state = {
      notification: 5,
name: "Only Fullstack"
    };
  }

Suppose we have fetched the notification count details and user name from the rest api and now we want to pass this information to <Hello> and <Notification> components.
class App extends Component {
  constructor() {
    this.state = {
      notification: 5,
      name: "Only Fullstack"
    };
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <Notification notification={this.state.notification} />
        <p>Start editing to see some magic happen :)</p>
      </div>
    );
  }
}

Component props in React

Components accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen. props are used to take an input form its parent component.
Here we are passing name as an input property to <Hello> component and notification as an input property to <Notification> component.

You can visit below link to get the latest code changes with state and props in React component or use below embedded editor to play.
React Component Example

state vs props in React

State
  • states are mutable.
  • states are associated with the individual components can't be used by other components.
  • states are initialize on component mount.
  • states are used for rendering dynamic changes within component.
Props
  • props are immutable.
  • you can pass props between components.
  • props are mostly used to communicate between components.You can pass from parent to child directly. For passing from child to parent you need use concept of lifting up states.
  • Functional Components in React
  • Have seen the Hello Component? no, please check again, Its bit different than the Notification component. Its called as Functional Component.

The simplest way to define a component is to write a JavaScript function:
export default function Hello(props) {
  return <h1>Hello, {props.name}</h1>;
}

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “function components” because they are literally JavaScript functions.

Functional vs Class Component in React

Class Component
Functional Component
Class-based Components uses ES6 class syntax.
Functional Component uses JavaScript functions.
Class components can have state to hold their current state.
Functional components cannot have state.
Class Component can use the lifecycle methods of react component.
Class Component cannot use the lifecycle methods of react component.
class Notification extends Component {
  constructor() {
    this.state = {
      component: "Notification"
    };
  }

  render() {
    return
        <div>
          <h4>
            I am coming from Component
          </h4>
        </div>
      ;
      }
}


export default function Hello(props) {
  return <h1>Hello, {props.name}</h1>;
}

Advantages of Functional Component in React

  1. Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
  2. You end up with less code
  3. It will get easier to separate container and presentational components because you need to think more about your component’s state if you don’t have access to setState() in your component
  4. The React team mentioned that there may be a performance boost for functional component in future React versions
  5. There is one difference is the syntax. A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element. A class component requires you to extend from React.Component and create a render function which returns a React element. This requires more code but will also give some benefits.

React Components Lifecycle

React has below life cycle methods.
  • componentWillMount is executed before rendering, on both the server and the client side.
  • componentDidMount is executed after the first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution such as setTimeout or setInterval. We are using it to update the state so we can trigger the other lifecycle methods.
  • componentWillReceiveProps is invoked as soon as the props are updated before another render is called. We triggered it from setNewNumber when we updated the state.
  • shouldComponentUpdate should return true or false value. This will determine if the component will be updated or not. This is set to true by default. If you are sure that the component doesn't need to render after state or props are updated, you can return false value.
  • componentWillUpdate is called just before rendering.
  • componentDidUpdate is called just after rendering.
  • componentWillUnmount is called after the component is unmounted from the dom. We are unmounting our component in main.js.
React Component Lifecycle Example


Output-

Lets go to our next tutorial where we will discuss below points :

Part 4 - Event Handling in React

In this tutorial, we will understand below topics - 
 - Why does onClick is not having a method parentheses?
 - Why do we need to bind event handlers in React?
 - Different ways to implement Event Handling in React
https://onlyfullstack.blogspot.com/2019/11/event-handling-in-react.html

Source Code
You can edit and play with the react examples on below stackblitz site - 
https://stackblitz.com/@onlyfullstack

React Tutorial
https://onlyfullstack.blogspot.com/2019/11/react-tutorial.html

Comments

Trending Tutorials

Trending Tutorials

WebSocket With Spring Boot and Angular 6 Tutorial

In this tutorial, we will understand What is WebSocket? Why to use WebSocket? Polling vs Server Sent Events vs WebSocket and WebSocket Example with Spring Boot + Angular 6 + STOMP

Code Coverage with JaCoCo Sonar and Maven

In this tutorial, we will understand the importance of code coverage and how can we setup the Sonar + JaCoCo + Maven to get the code coverage. We will look into Setting up Sonar Server Locally, Integrate JaCoCo plugin with Sonar and Maven for Code Coverage, Find Code Coverage in Eclipse : EclEmma Configuration

Java 8 Features

Learn all about Java 8 features in details

Lambda Expression in Java 8

Ever wonder what Lambda Expression is? What Lambda expressions are compiled to? if no then you should go through this tutorial to know more about Lambda and how they are different than anonymous class.