Certainly! Creating a simple calculator application in React involves setting up a React project, creating components, and handling state to perform calculations. Here’s a basic example to get you started:
- Setup React Project:
If you haven’t already, set up a new React project using Create React App. Open your terminal and run:
npx create-react-app react-calculator
cd react-calculator
- Create Components:
In thesrc
folder, create the following components:
App.js
Calculator.js
Button.js
Display.js
- Button.js:
Create a simple button component:
// Button.js
import React from 'react';
const Button = ({ label, onClick }) => (
<button onClick={() => onClick(label)}>{label}</button>
);
export default Button;
- Display.js:
Create a display component to show the calculator’s input and result:
// Display.js
import React from 'react';
const Display = ({ input, result }) => (
<div>
<div>{input}</div>
<div>{result}</div>
</div>
);
export default Display;
- Calculator.js:
Implement the calculator component that will handle the logic:
// Calculator.js
import React, { useState } from 'react';
import Button from './Button';
import Display from './Display';
const Calculator = () => {
const [input, setInput] = useState('');
const [result, setResult] = useState('');
const handleButtonClick = (label) => {
if (label === '=') {
try {
setResult(eval(input).toString());
} catch (error) {
setResult('Error');
}
} else if (label === 'C') {
setInput('');
setResult('');
} else {
setInput(input + label);
}
};
const buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+',
'C',
];
return (
<div>
<Display input={input} result={result} />
<div>
{buttons.map((label) => (
<Button key={label} label={label} onClick={handleButtonClick} />
))}
</div>
</div>
);
};
export default Calculator;
- App.js:
Use theCalculator
component in your mainApp
component:
// App.js
import React from 'react';
import Calculator from './Calculator';
function App() {
return (
<div>
<h1>React Calculator</h1>
<Calculator />
</div>
);
}
export default App;
- Run Your App:
Finally, run your React app:
npm start
Visit http://localhost:3000
in your browser to see the basic calculator application in action. You can further enhance and style it based on your requirements.
Show Comments