Published in


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.

before clicking on the button
after clicking the button


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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Saranjeet Singh

I write tutorials on Python, JavaScript, React, and Django. I write for InPlainEnglish and TheStartUp .