Created
March 24, 2019 07:13
-
-
Save hoseinhamzei/64a4365d6b0ece7e1246b15462e74e2c to your computer and use it in GitHub Desktop.
Counter component with react hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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