Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Use Variables within Classes

Mar 19, 2020 • 10 Minute Read

Introduction

Variables store data in terms of values that may or may not be modified into the current context. They can be declared using the various data types available depending on the programming or scripting language.  In this guide, we will learn how to declare and work with various types of variables within classes, including the this keyword, static, props, and state variables.

Using the This Keyword

The scope of a variable may be different based on the situation, but the this keyword typically references a JavaScript element depending on the different scope or context where it’s being used.

For example, if you console the keyword this into the global scope, then you will be able to get the empty object.

      console.log(this);
    

But if you want to use inbuilt JavaScript functionalities or browser-based functionalities, then the window object can be used.

      window.alert("this is test alert")
    

The same applies to a function using the global scope.

      const thisFunction = function () {
 return "Hello World";
}
let msg = thisFunction()
console.log(msg)
    

In React component classes, the methods that will refer to class attributes, such as props and state, can be defined into the current context. However, for the methods of the components, you have access to this.state and this.props, and you need to bind the React component for this context to those methods.

For example, say you have one form with the submit method.

      import React, { Component } from "react";
import { render } from "react-dom";

class App extends Component {

  constructor() {
    super();
    this.state = {
      name: "React",
    };
    // Binding method
    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onFormSubmit() {
    console.log("Form Submitted");
  }
  
  render() {
    return (
      <div>
        <div>
          <form>
            <input type="text" />
            <button onClick={this.onFormSubmit}>Submit</button>
          </form>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

Here in this example, the component has one method called onFormSubmit(), but notice the constructor of the class. The method is bound to the current context with the use of the ‘this’ keyword.

Binding the this keyword to the class method enables you to access the props and state for the component with this.props and this.state.

So when you try to access any props after binding, use the props value as given in the example below.

      onFormSubmit() {
    console.log(this.props.formValues);
  }
    

Using Static as the Variable Type

Static variables can be used within React classes, just like other different kinds of variables can access it. Still, the difference is that the scope of the variables can be modified for static variables, and it cannot be modified.

For example, if you use a static or fixed value, it can be declared and used.

      import React, { Component } from "react";
import { render } from "react-dom";

class App extends Component {
  // Declaring static variable
  static num1 = 3.1416;

  constructor() {
    super();
  }

  render() {
    return (
      <div>
        <div>Accessing local static number variable : {this.num1}</div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

In the above example, there is one static variable called num1 whose value is fixed. This means no one can change its value into the current component, but they can use it for the rendering purpose.

In the same way, the state object can also be used as a static value.

      import React, { Component } from "react";
import { render } from "react-dom";

class App extends Component {

   state = {
    name: 'Hello World',
    age: '30'
  };

  render() {
    const { name, age } = this.state;
    console.log(this.state)
    return (
      <div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

In the above example, the state object will be static, and this means we can pass it to the child component and it will act as a constant value.

Using State Variables

State is one of the widely used terms in React. It is used to manage the component-based data transmission where you can declare the key-value pair and modify it based on the functional requirements.

The state can be declared into the constructor or as a static object.

      constructor() {
    super();
    this.state = {
      name: "React",
      students: [
        {
          id: 123,
          name: "Student 1"
        },
        {
          id: 456,
          name: "Student 2"
        },
        {
          id: 789,
          name: "Student 3"
        }
      ]
    };
  }
    

In this example, the state variable is created, called students, and consists of an array of objects and can be accessed like this.:

      render() {
    // Using state value
    const { students } = this.state;
    return (
      <div>
        // using state value for rendering
      </div>
    );
  }
    

As you can see, the state value can be accessed through this.state, which is bound to the current class context by using the this keyword.

Assigning Props Values to the Variables

Props are read-only properties, or the instance of the properties for the class, and they are one way to pass data from a parent component to a child component.

Commonly, the props as a variable are used to pass dynamic or processed data to a child component so the child component can consume and process it.

For example, there is one array of objects in the parent component, as explained below in the example.

      constructor() {
    super();
    this.state = {
      name: "React",
      students: [
        {
          id: 123,
          name: "Student 1"
        },
        {
          id: 456,
          name: "Student 2"
        },
        {
          id: 789,
          name: "Student 3"
        }
      ]
    };
  }
    

Now you can pass the state variable, students, to the child component.

      import React, { Component } from "react";
import { render } from "react-dom";
import Demo1 from './Demo';

class App extends Component {

  constructor() {
    super();
    this.state = {
      students: [
        {
          id: 123,
          name: "Student 1"
        },
        {
          id: 456,
          name: "Student 2"
        },
        {
          id: 789,
          name: "Student 3"
        }
      ]
    };
  }

  render() {
    return (
      <div>
        <Demo1 
          students={this.state.students}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

In this example, Demo1 is one of the child components. Along with the child component, the additional property is going to be passed students, and from the child component, you can access the props value like this:

      import React, { Component } from "react";

class Demo1 extends Component {

  constructor() {
    super();
    this.state = {
      name: "React",
    };
  }

  render() {
    const { students } = this.props;

    return (
      <div>
        {
          students.map((item) => {
            return (
              <div>Student name is : {item.name}</div>
            )
          })
        }
      </div>
    );
  }
}

export default Demo1
    

As you can see in the above example, there is one additional property called students coming from the parent component. Into the render method, the map is implemented to iterate through the array of objects.

This is one of the standard ways to pass data from a parent component to a child component as a form of props.

Const as a Variable

The variable const is one of the primary options to store static data or values for a specific reason. In most cases, the const value won’t be used for modification.

You can declare and use the const variable as explained below.

      render() {
    const { students } = this.props;
    const PI = 3.1416;
    PI = 45.45;
    return (
      <div>
        <p>Value of PI is : {PI}</p>
      </div>
    );
  }
    

As you can see, The PI variable Is being modified. This means you can modify the const variable and transform it based on your functional requirements.

The better way to use const in React is to store the state or props value like this:

      const { students } = this.props;
const { name, age } = this.state;
    

Conclusion

In this guide, you learned how to declare and use variables such as local, global, static, state, and props as a variable.

Developers can adopt various options to store data for rendering into a React component. I hope this guide was helpful to you. Thanks for reading.

Learn More