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.




From Web Development to Machine Learning, we will put a lot of free materials for anyone who wants to learn to code.

Recommended from Medium

(MERN-1)Node js with server

Fire CMS as a Single Page Application

Some react concept -Day 2

A quarrel over a sand mound

JavaScript: Sets vs. Arrays

Say Hello to the New and Improved Choreo Experience!

Next.js export and weird flickering on Chrome

IFTTT: Forex trading for beginners pdf South Africa

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

Saranjeet Singh

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

More from Medium

React Advance: Code Splitting

React.memo() vs. useMemo()

Understanding React Hooks