hooks lifecycle react code example
Example 1: set state
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>
)
}
}
Example 2: set state
setState({ searchTerm: event.target.value })
Example 3: react lifecycle hooks
class Content extends React.Component {
// ...
componentWillMount() {
this.setState({ activities: data });
}
// ...
}
Example 4: components react to hooks
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 5: 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>
)
}
}