Answers for "reactjs setstate"

5

how to use setstate

class App extends React.Component {

state = { count: 0 }

handleIncrement = () => {
  this.setState({ count: this.state.count + 1 })
}

handleDecrement = () => {
  this.setState({ count: this.state.count - 1 })
}
  render() {
    return (
      <div>
        <div>
          {this.state.count}
        </div>
        <button onClick={this.handleIncrement}>Increment by 1</button>
        <button onClick={this.handleDecrement}>Decrement by 1</button>
      </div>
    )
  }
}
Posted by: Guest on April-27-2020
15

state react

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
Posted by: Guest on March-13-2020
3

setstate in react

Functional Component
const [counter, setCounter] = useState(0);

setCouter(counter + 1);
Posted by: Guest on March-22-2021
1

react setState

this.setState({
      date: new Date()
    });
Posted by: Guest on December-09-2020
1

react setState

incrementCount() {
  // Note: this will *not* work as intended.
  this.setState({count: this.state.count + 1});
}

handleSomething() {
  // Let's say `this.state.count` starts at 0.
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();
  // When React re-renders the component, `this.state.count` will be 1, but you expected 3.

  // This is because `incrementCount()` function above reads from `this.state.count`,
  // but React doesn't update `this.state.count` until the component is re-rendered.
  // So `incrementCount()` ends up reading `this.state.count` as 0 every time, and sets it to 1.

  // The fix is described below!
}
Posted by: Guest on January-06-2021
-1

react lifecycle hooks

class ActivityItem extends React.Component {
  render() {
    const { activity } = this.props;

    return (
      <div className='item'>
        <div className={'avatar'}>
          <img
            alt='avatar'
            src={activity.actor.avatar_url} />
        </div>

        <span className={'time'}>
          {moment(activity.created_at).fromNow()}
        </span>
        
        <p>{activity.actor.display_login} {activity.payload.action}</p>
        <div className={'right'}>
          {activity.repo.name}
        </div>
      </div>
    )
  }
}
Posted by: Guest on October-11-2020

Browse Popular Code Answers by Language