Create a Simple Calculator App in React Js | Interview Question
In this post, you will learn about how to create simple calculator App in React js using hooks.
Following is the UI functionality of the application.
Sample Code:
A) App.js
import React, { useState } from 'react';
import './style.css';
const Header = () => {
return <div id="header">Simple Calculator</div>;
};
export default function App() {
const buttons = [
{ id: 1, name: '7' },
{ id: 2, name: '8' },
{ id: 3, name: '9' },
{ id: 4, name: 'Del' },
{ id: 5, name: '4' },
{ id: 6, name: '5' },
{ id: 7, name: '6' },
{ id: 8, name: '+' },
{ id: 9, name: '1' },
{ id: 10, name: '2' },
{ id: 11, name: '3' },
{ id: 12, name: '-' },
{ id: 13, name: '.' },
{ id: 14, name: '0' },
{ id: 15, name: '/' },
{ id: 16, name: '*' },
];
const [text, setText] = useState('');
const [show, setShow] = useState('');
const onClickDel = (name) => {
let numStr = text.substring(text.length - 1, 0);
setText(numStr);
};
const onClickGeneral = (name) => {
let numStr = text + name;
setText(numStr);
};
const submit = () => {
let evalStatement;
try {
evalStatement = eval(text);
setShow(evalStatement);
} catch (err) {
setShow('Error');
}
};
const reset = () => {
setShow('');
setText('');
};
return (
<div id="mainDiv">
<Header />
<input id="input" type="text" value={text} />
<input id="output" type="text" value={show} />
<div>
{buttons &&
buttons.length &&
buttons.map((item) => {
return (
<div
id="circle"
onClick={
item.name == 'Del'
? () => {
onClickDel(item.name);
}
: () => {
onClickGeneral(item.name);
}
}
key={item.id}
>
{item.name}
</div>
);
})}
</div>
<button id="reset" onClick={reset}>
{' '}
Reset{' '}
</button>
<button id="submit" onClick={submit}>
{' '}
Submit{' '}
</button>
</div>
);
}
CSS:
B) styles.css
#mainDiv {
border: 1px solid black;
width: 320px;
height: 330px;
background-color: orange;
border-radius: 30px;
}
#reset,
#submit {
border: 1px solid black;
float: left;
width: 80px;
margin-left: 25px;
margin-right: 25px;
margin-top: 10px;
font-weight: bold;
}
#input,
#output {
width: 260px;
height: 30px;
margin-top: 10px;
margin-left: 25px;
margin-right: 25px;
margin-bottom: 2px;
border-radius: 5px;
font-weight: bold;
}
#circle {
width: 30px;
height: 30px;
background-color: rgb(162, 162, 162);
border-radius: 10px;
float: left;
text-align: center;
margin-top: 10px;
margin-left: 25px;
margin-right: 25px;
margin-bottom: 2px;
line-height: 30px;
font-weight: bold;
}
#header {
margin-left: 25px;
margin-right: 25px;
margin-top: 10px;
text-align: center;
}
Happy Learning!! Happy Coding!!
Comments