Skip to content

Instantly share code, notes, and snippets.

@Karajna
Created January 4, 2021 19:26
Show Gist options
  • Save Karajna/03f8735971a0918c7885899a63e2b029 to your computer and use it in GitHub Desktop.
Save Karajna/03f8735971a0918c7885899a63e2b029 to your computer and use it in GitHub Desktop.
Karyna's Calculator
<div id='root'></div>
function App() {
const [expression, setExpression]= React.useState("");
const [answer, setAnswer]=React.useState(0);
const display = (symbol) => {
if (expression[0]=="0") {
setExpression('')
} else if (!/\./.test(expression)) {
setExpression((prev)=>prev+symbol)
}
if (expression[expression.length-1] =="=")
{ if (/[0-9.]/.test(symbol))
{setExpression(symbol)}
else {setExpression(answer+symbol)}
}
}
const calculate = () => {
setAnswer(eval(expression))
setExpression(prev=> prev+"=")
}
const clearAll= () =>{
setExpression('')
setAnswer(0);
}
return (
<div class="container">
<div class="calculator">
<div id="displayMain">
<input placeholder="0" id="display" type="text" value={expression}/>
<div className="total">{answer}</div>
</div>
<div className="keys">
<button id="add" onClick = {() => display("+")}>+</button>
<button id="subtract" onClick = {() => display("-")}>-</button>
<button id="multiply" onClick = {()=>display("*")}>&times;</button>
<button id="divide" onClick = {()=>display("÷")}>÷</button>
<button id="seven" onClick = {()=>display("7")}>7</button>
<button id="eight" onClick = {()=>display("8")}>8</button>
<button id="nine" onClick = {()=>display("9")}>9</button>
<button id="four" onClick = {()=>display("4")}>4</button>
<button id="five" onClick = {()=>display("5")}>5</button>
<button id="six" onClick = {()=>display("6")}>6</button>
<button id="one" onClick = {()=>display("1")}>1</button>
<button id="two" onClick = {()=>display("2")}>2</button>
<button id="three" onClick = {()=>display("3")}>3</button>
<button id="zero" onClick = {()=>display("0")}>0</button>
<button id="decimal" onClick = {()=>display(".")}>.</button>
<button id="clear" onClick = {clearAll}>AC</button>
<button id="equals" onClick = {calculate}>=</button>
</div>
</div>
</div>
)}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment