build a counter using props react 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: 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')
);