In this chapter, we will learn:
React state
Creating the state Object
import React, { Component } from 'react'
class StudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
firstName: "Ramesh"
}
}
render() {
return (
<div>
<h1> Hello Student</h1>
</div>
)
}
}
export default StudentComponent
import React, { Component } from 'react'
class StudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
firstName: "Ramesh",
lastName:"Fadatare",
rollNo: 123,
age: 20,
books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
}
}
render() {
return (
<div>
<h1> Hello Student</h1> <hr/>
</div>
)
}
}
export default StudentComponent
Using the state Object
this.state.propertyname
import React, { Component } from 'react'
class StudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
firstName: "Ramesh",
lastName:"Fadatare",
rollNo: 123,
age: 20,
books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
}
}
render() {
return (
<div>
<h1> Student Details</h1> <hr/>
<h3> First Name: {this.state.firstName }</h3>
<h3> Last Name: {this.state.lastName }</h3>
<h3> Roll No: {this.state.rollNo } </h3>
<h3> Age: {this.state.age }</h3>
<h3> {this.state.books} </h3>
</div>
)
}
}
export default StudentComponent
import React from 'react';
import logo from './logo.svg';
import './App.css';
import StudentComponent from './components/StudentComponent';
function App() {
return (
<div className="App">
<header className="App-header">
<StudentComponent />
</header>
</div>
);
}
export default App;
Hit URL http://localhost:3000/ in Browser
Changing the state Object using setState() Method
import React, { Component } from 'react'
class StudentComponent extends Component {
constructor(props) {
super(props)
this.state = {
firstName: "Ramesh",
lastName:"Fadatare",
rollNo: 123,
age: 20,
books: ["C programming", "C++ programming", "Data Structure and Algorithms"]
}
}
updateStudent(){
this.setState({
rollNo: 124,
age: 21
})
}
render() {
return (
<div>
<h1> Student Details</h1> <hr/>
<h3> First Name: {this.state.firstName }</h3>
<h3> Last Name: {this.state.lastName }</h3>
<h3> Roll No: {this.state.rollNo } </h3>
<h3> Age: {this.state.age }</h3>
<h3> {this.state.books} </h3>
<button type="button" onClick={() => this.updateStudent()} >Update Student Details</button>
</div>
)
}
}
export default StudentComponent
What's Next?
❮ Previous Chapter Next Chapter ❯
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner


Comments
Post a Comment
Leave Comment