react counter class component code example
Example 1: 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 2: 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>
);
}