react counter code example
Example 1: simple counter react
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
export const Counter = (props) => {
const [count, setCount ] = useState(0)
return (
<div id="mainArea">
button count: <span>{count}</span>
<button id="mainButton" onClick={() => {setCount(count + 1)}}>Increase</button>
</div>
);
}
ReactDOM.render(
<Counter />,
document.getElementById('root')
);
Example 2: 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 3: counter composant react
import React, { useState } from 'react';
function Example() {
return (
<div>
<p>Vous avez cliqué {count} fois</p>
<button onClick={() => setCount(count + 1)}>
Cliquez ici
</button>
</div>
);
}
Example 4: simple counter react
import React from 'react';
import ReactDOM from 'react-dom';
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count : 0
}
this.increment = this.increment.bind(this);
}
increment() {
this.setState({count:this.state.count+1});
}
render() {
return (
<div id="mainArea">
button count: <span>{this.state.count}</span>
<button onClick={this.increment} id="mainButton">Increase</button>
</div>
);
}
}
ReactDOM.render(
<Counter />,
document.getElementById('root')
);