Creating a React App
React is a popular JavaScript library for building user interfaces. It allows you to create reusable UI components and manage the state of your application efficiently. This article will guide you through creating a React app and building a simple calculator as a practical example.
What is a React App?
A React app is a single-page application (SPA) built using the React library. It consists of reusable UI components that are rendered dynamically in the browser. React uses a virtual DOM to efficiently update the actual DOM, resulting in improved performance and a smoother user experience.
Key concepts in React include:
- Components: Reusable building blocks of the UI.
- JSX: A syntax extension to JavaScript that allows you to write HTML-like code within JavaScript.
- State: Data that can change over time and trigger re-renders of components.
- Props: Data passed from parent components to child components.
- Virtual DOM: An in-memory representation of the actual DOM, used for efficient updates.
Prerequisites
- Basic knowledge of HTML, CSS, and JavaScript
- Node.js and npm (Node Package Manager) installed
Creating a New React App
You can create a new React app using Create React App, a popular tool that sets up a modern React development environment.
-
Using Create React App:
Open your terminal and run the following command:
bashnpx create-react-app calculator-app cd calculator-appThis command creates a new React app named
calculator-appand navigates into the project directory. -
Starting the Development Server:
Run the following command to start the development server:
bashnpm startThis will open your React app in the browser, usually at
http://localhost:3000.
Building a Simple Calculator
Now, let's build a simple calculator app to demonstrate React concepts.
-
Clean Up the Project:
Remove unnecessary files from the
srcdirectory, such asApp.css,App.test.js,logo.svg, andsetupTests.js. -
Update
index.js:Update the
src/index.jsfile to render theAppcomponent:javascriptimport React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <App /> </React.StrictMode> ); -
Create
App.js:Create a new file named
src/App.jswith the following content:javascriptimport React, { useState } from 'react'; import './App.css'; function App() { const [input, setInput] = useState(''); const [result, setResult] = useState(''); const handleButtonClick = (value) => { setInput((prevInput) => prevInput + value); }; const handleCalculate = () => { try { setResult(eval(input).toString()); } catch (error) { setResult('Error'); } }; const handleClear = () => { setInput(''); setResult(''); }; return ( <div className="calculator"> <input type="text" value={input} readOnly /> <div className="result">{result}</div> <div className="buttons"> <button onClick={handleClear}>Clear</button> <button onClick={() => handleButtonClick('7')}>7</button> <button onClick={() => handleButtonClick('8')}>8</button> <button onClick={() => handleButtonClick('9')}>9</button> <button onClick={() => handleButtonClick('+')}>+</button> <button onClick={() => handleButtonClick('4')}>4</button> <button onClick={() => handleButtonClick('5')}>5</button> <button onClick={() => handleButtonClick('6')}>6</button> <button onClick={() => handleButtonClick('-')}>-</button> <button onClick={() => handleButtonClick('1')}>1</button> <button onClick={() => handleButtonClick('2')}>2</button> <button onClick={() => handleButtonClick('3')}>3</button> <button onClick={() => handleButtonClick('*')}>*</button> <button onClick={() => handleButtonClick('0')}>0</button> <button onClick={() => handleButtonClick('.')}>.</button> <button onClick={handleCalculate}>=</button> <button onClick={() => handleButtonClick('/')}>/</button> </div> </div> ); } export default App; -
Create
App.css:Create a new file named
src/App.csswith the following content:css.calculator { width: 300px; margin: 0 auto; padding: 20px; border: 1px solid #ccc; border-radius: 5px; } .calculator input { width: 100%; margin-bottom: 10px; padding: 10px; font-size: 20px; border: 1px solid #ccc; border-radius: 5px; } .calculator .result { margin-bottom: 10px; padding: 10px; font-size: 20px; text-align: right; border: 1px solid #ccc; border-radius: 5px; } .calculator .buttons { display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 5px; } .calculator .buttons button { padding: 10px; font-size: 20px; border: 1px solid #ccc; border-radius: 5px; cursor: pointer; }
Explanation
useStateHook: Used to manage the input and result values.handleButtonClick: Appends the clicked button's value to the input.handleCalculate: Evaluates the input usingeval()and sets the result. Includes error handling for invalid expressions.handleClear: Clears the input and result.- JSX Structure: Defines the layout of the calculator, including the input field, result display, and buttons.
- CSS Styling: Provides basic styling for the calculator.
Conclusion
This article demonstrated how to create a React app using Create React App and build a simple calculator. You learned about React components, state management, event handling, and JSX. You can expand upon this foundation by adding more features and styling to create more complex and interactive applications.