Component State In react

Aug 03, 2019

Internal component state, also known as local state, allows you to save, modify and delete properties that are stored in your component. The ES6 class component can use a constructor to initialize internal component state later on. The constructor is called only once when the component initializes. Let’s introduce a class constructor.

class App extends Component {
constructor(props) {
super(props);
}
...
}

When having a constructor in your ES6 class component, it is mandatory to call super(); because the App component is a subclass of Component. Hence the extends Component in your App component declaration. You will learn more about ES6 class components later on. You can call super(props); as well. It sets this.props in your constructor in case you want to access them in the constructor. Otherwise, when accessing this.props in your constructor, they would be undefined. You will learn more about the props of a React component later on. Now, in your case, the initial state in your component should be the sample list of items.

const list = [
{
    title: 'React',
    url: 'https://facebook.github.io/react/',
    author: 'Jordan Walke',
    num_comments: 3,
    points: 4,
    objectID: 0,
    },
    ...
];
class App extends Component {
    constructor(props) {
    super(props);
    this.state = {
    list: list,
    };
    }
...
}

The state is bound to the class by using the this object. Thus you can access the local state in your whole component. For instance, it can be used in the render() method. Previously you have mapped a static list of items in your render() method that was defined outside of your component. Now you are about to use the list from your local state in your component.

render() {
    return (
            <div className="App">
                {this.state.list.map(item =>
                    <div key={item.objectID}>
                    <span>
                    <a href={item.url}>{item.title}</a>
                    </span>
                    <span>{item.author}</span>
                    <span>{item.num_comments}</span>
                <span>{item.points}</span>
            </div>
        )}
        </div>
    );
    }
}

The list is part of the component now. It resides in the internal component state. You could add items, change items or remove items in and from your list. Every time you change your component state, the render() method of your component will run again. That’s how you can simply change your internal component state and be sure that the component re-renders and displays the correct data that comes from the local state

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning