Tuesday, August 7, 2018

setState example in React

The setState() method is used to change the state values of a React Component. After the component is initialized we can call setState to change specific state properties, setState() updates the components state and triggers Render() of the component. Based on the updates in state the component in re-rendered.

In this example we will initialize a component with a property show with default value false. We have a button Show/Hide the click event of the button toggles the value of the state using setState(), based on the current value of the state property the component will show/hide the message "Hello State".
import React, {Component} from 'react';
import ReactDOM from 'react-dom';

class HelloState extends Component {
  constructor(props) {
    this.state = {
show: false
this.handleClick = this.handleClick.bind(this);

  handleClick() { 
    this.setState({show : !this.state.show});

  render() {
return (
<button onClick = {this.handleClick}> Show/Hide </button><br/>
{ this.state.show ?
<span>Hello State</span>

ReactDOM.render(<HelloState />, document.getElementById('app'));

Search Flipkart Products:

No comments: