Skip to content

Instantly share code, notes, and snippets.

@hoseinhamzei
Created March 24, 2019 07:13
Show Gist options
  • Save hoseinhamzei/64a4365d6b0ece7e1246b15462e74e2c to your computer and use it in GitHub Desktop.
Save hoseinhamzei/64a4365d6b0ece7e1246b15462e74e2c to your computer and use it in GitHub Desktop.
Counter component with react hooks
import React,{useState} from 'react';
// create a stateless component
function Counter(){
// count state with usestate hook and setCount method
const [count, setCount] = useState(0);
// render component
return(
<div>
<Cshow cnt={count}/>
<div>
<button onClick={()=>change('-')}>-</button>
<button onClick={()=>change('+')}>+</button>
</div>
</div>
)
// change count based on operation
function change(op){
if(op === '+'){
setCount(count+1);
}
else if(op === '-' && count > 0){
setCount(count-1);
}
}
}
function Cshow(props){
return(
<h1>count:{props.cnt}</h1>
);
}
export default Counter;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment