react js counter component 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: counter app in react using class component
import React from 'react';
import './App.css';
export default class Parent extends React.Component{
constructor(props){
super();
this.state={
value:0
}
}
execute1(){
this.setState({
value:this.state.value+1
})
}
execute2(){
this.setState({
value:this.state.value-1
})
}
render(){
return(
<div>
<Child1 value={this.state.value} ></Child1>
<Child2 value={this.state.value}></Child2>
<button onClick={this.execute1.bind(this)}>click me</button>
<button onClick={this.execute2.bind(this)}>click me</button>
</div>
)
}
}
class Child1 extends React.Component{
render(){
return(
<div className="modify">
<label>{this.props.value}</label>
</div>
)
}
}
class Child2 extends React.Component{
render(){
return(
<div className="modify">
<label>{this.props.value}</label>
</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>
);
}