React JS Tutorial - State

In this tutorial, we will learn about state in React components. React components have a built-in state object that allows you to store property values that belong to the component.

The state object is a crucial part of React components, as it enables you to store and manage data that is specific to the component. Let's add state to our Post component.

Go to your project and open the Post component. Add the state object as follows:


import React, { Component } from 'react'

class Post extends Component {
state={
name:'Jennifer',
age:25
}
render() {
return (
<div>
<h1>This is Post Component.</h1>
</div>
)
}
}

export default Post;

Now, let's access this state in the component's render method. Inside the curly brackets, write the following code:


import React, { Component } from 'react'

class Post extends Component {
state={
name:'Jennifer',
age:25
}
render() {
return (
<div>
<h1>This is Post Component.</h1>
<p>Name: {this.state.name} </p>
<p>Age: {this.state.age} </p>
</div>
)
}
}

export default Post;

Save the file and let's check the output. Switch to your browser, and you should see the name and age displayed inside the Post component.

Using Arrays in State

We can also add arrays to the state object. To do this, simply write the following code:


state={
skills:['react','javascript','html']
}

Now, let's print this array inside the component's render method. Type the following code inside the render return statement:


<p>Skills: {this.state.skills} </p>

Save the file and let's check the output. You should see the skills array displayed.

To separate each skill with a comma, we can use the join function and pass a comma as an argument. Update the code as follows:


{this.state.skills.join(',')}

Save the file and let's check the output again. Now, you should see the array elements displayed as a comma-separated list.

That's it! You have successfully learned how to use state in React components. By following these steps, you can store and manage data in your React components using the state object.