Day 9: setState in React continues
Yesterday, we saw how arrow functions and states work in the React. Today, we will see how to use setState to change the data triggered by an event handler.
How not to use state
Unlike props, we can use
this.state.name = 'Dave'
it in our program. This won’t work because under the hood, React has no idea you changed the state. The right way to do is:
this.setState({name:'Dave', roll:'2'})
this code change at the event handler will produce the desired result.
so, our student.js file will look like this:
import React , {Component} from 'react' ;class Student extends React.Component { constructor(props) { super(props); this.state = { name : 'John', roll : this.props.roll};}handleClick = () =>{ this.setState({name:'Dave', roll:'2'})};render() {return ( <div> <h1>Hey, {this.state.name}, your roll number is {this.state.roll} </h1> <button onClick = {this.handleClick}>click here</button></div>)}}export default Student
our App.js will remain the same.
Conclusion:
from the last lesson and this lesson, we have learned the right way to change the state of the program. And how data flows in React.
Photo by Anas Alshanti on Unsplash