Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to map state in ReactJS

Introduction to ReactJS

ReactJS, or just React, is a JavaScript library for building user interfaces, mainly for single-page applications. It allows developers to create reusable UI components. React is maintained by Facebook and a community of individual developers and companies.

What is State in React?

In simple terms, state in React is a JavaScript object that stores component's dynamic data and enables a component to keep track of changes between renders. It is an integral part of every React component. When the state of a component changes, the component responds by re-rendering.

Think of state as a container that holds data which can change over time and affect the behavior of your application. It's like a water jug that can be filled, emptied, and refilled over time, influencing how thirsty you are.

Creating a React Component with State

To explain how we can map state in React, we first need to understand how to create a stateful React component. Let's start by creating a simple component to show a list of names. We'll use a class-based component for this example.

import React, { Component } from 'react';

class NameList extends Component {
  constructor() {
    super();
    this.state = {
      names: ['John', 'Jane', 'James', 'Jasmine']
    };
  }

  render() {
    return (
      <div>
        {/* We will map names here */}
      </div>
    );
  }
}

export default NameList;

In the code above, we have a simple 'NameList' component with a state object that includes an array of names.

Mapping State in React

Now that we have a component with state, let's learn how to map this state in our render method to display the list of names. The JavaScript map() function is a powerful tool that allows us to iterate over arrays and manipulate their data.

Imagine you're at a party and you're the host. You have a list of guests (our names array), and you want to introduce each one to the others (map over the array). The map() function allows you to "introduce" (process) each guest (array element) one by one.

In React, we can use the map() function inside our render method to process and display each item of our state array. Here's how:

render() {
  return (
    <div>
      {this.state.names.map((name, index) => {
        return <p key={index}>{name}</p>
      })}
    </div>
  );
}

In the code above, we're mapping over this.state.names and for each name, we're returning a paragraph element with the name inside it. The key attribute is a special string attribute that needs to be included when creating lists of elements in React. It helps React identify which items have changed, are added, or are removed and should be a unique value.

Now, our 'NameList' component will render a new paragraph for each name in its state.

Changing State

State in React is mutable, meaning it can be changed. However, there's a golden rule in React: Never mutate state directly. Instead, we use the setState() function.

Let's add a button to our 'NameList' component that adds a new name to our list:

class NameList extends Component {
  constructor() {
    super();
    this.state = {
      names: ['John', 'Jane', 'James', 'Jasmine']
    };
    this.addName = this.addName.bind(this);
  }

  addName() {
    this.setState({ names: [...this.state.names, 'Jerry'] });
  }

  render() {
    return (
      <div>
        {this.state.names.map((name, index) => {
          return <p key={index}>{name}</p>
        })}
        <button onClick={this.addName}>Add Name</button>
      </div>
    );
  }
}

export default NameList;

In the code above, we've added a addName method that uses setState to add a new name to our list. We've also added a button that calls this method when clicked. Now, every time you click the "Add Name" button, 'Jerry' will be added to the list of names.

Conclusion

Mapping state in ReactJS allows us to work with dynamic data, which can change over time and affect the component's behavior and render. It's a crucial concept in React and understanding it is vital to creating dynamic and interactive user interfaces in React.

Remember, the state in React is like a water jug that can be filled, emptied, and refilled over time, influencing how thirsty you are. And the map function is like introducing each guest at a party one by one. With these concepts and examples, you're now ready to create more complex and interactive applications using state in React. Happy coding!