state react.js code example
Example 1: state with react functions
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 2: state with react functions
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>
);
}
}
Example 3: what is state in react
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
Example 4: props and state react
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render( element, document.getElementById('root') );}
setInterval(tick, 1000);
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>
)
}
}