{"id":3944,"date":"2023-11-04T23:13:57","date_gmt":"2023-11-04T23:13:57","guid":{"rendered":"http:\/\/localhost:10003\/how-to-build-a-calculator-app-with-react-and-redux\/"},"modified":"2023-11-05T05:48:26","modified_gmt":"2023-11-05T05:48:26","slug":"how-to-build-a-calculator-app-with-react-and-redux","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-build-a-calculator-app-with-react-and-redux\/","title":{"rendered":"How to Build a Calculator App with React and Redux"},"content":{"rendered":"
In this tutorial, we will be building a simple calculator app using React and Redux. The calculator will have basic functionality such as addition, subtraction, multiplication, and division. The app will also have a history panel to display the previous calculations.<\/p>\n
To follow along with this tutorial, it is recommended to have a basic understanding of JavaScript, React, and Redux. You will also need to have Node.js installed on your machine.<\/p>\n
First, let’s set up the project by creating a new directory and initializing a new React project:<\/p>\n
mkdir calculator-app\ncd calculator-app\nnpx create-react-app .\n<\/code><\/pre>\nNow, let’s install the required dependencies for Redux:<\/p>\n
npm install redux react-redux\n<\/code><\/pre>\nProject Structure<\/h3>\n
Inside the src<\/code> directory, delete all the default files except for App.js<\/code> and index.js<\/code>.<\/p>\nCreate a new directory called redux<\/code> inside the src<\/code> directory. Inside the redux<\/code> directory, create the following files:<\/p>\n\nactions.js<\/code>: This file will define the actions for our calculator app.<\/li>\nreducers.js<\/code>: This file will define the reducers for our app.<\/li>\nstore.js<\/code>: This file will create the Redux store.<\/li>\n<\/ul>\nFinally, update the App.js<\/code> and index.js<\/code> files to reflect the following changes.<\/p>\nApp.js<\/code>:<\/p>\nimport React from 'react';\nimport Calculator from '.\/Calculator';\n\nfunction App() {\n return (\n <div className=\"App\">\n <Calculator \/>\n <\/div>\n );\n}\n\nexport default App;\n<\/code><\/pre>\nindex.js<\/code>:<\/p>\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport { Provider } from 'react-redux';\nimport store from '.\/redux\/store';\nimport '.\/index.css';\nimport App from '.\/App';\n\nReactDOM.render(\n <Provider store={store}>\n <App \/>\n <\/Provider>,\n document.getElementById('root')\n);\n<\/code><\/pre>\nBuilding the Calculator Component<\/h2>\n
Now, let’s start building the calculator component. Create a new file called Calculator.js<\/code> in the src<\/code> directory and update it with the following code:<\/p>\nimport React, { useState } from 'react';\nimport { connect } from 'react-redux';\nimport { bindActionCreators } from 'redux';\nimport { addNumber, clear, equals } from '.\/redux\/actions';\n\nfunction Calculator(props) {\n const [input, setInput] = useState('');\n\n const handleClick = (value) => {\n setInput(input + value);\n };\n\n const handleClear = () => {\n setInput('');\n props.clear();\n };\n\n const handleEqual = () => {\n props.equals(input);\n setInput('');\n };\n\n return (\n <div>\n <input type=\"text\" value={input} disabled \/>\n <br \/>\n <button onClick={() => handleClick('1')}>1<\/button>\n <button onClick={() => handleClick('2')}>2<\/button>\n <button onClick={() => handleClick('3')}>3<\/button>\n <button onClick={() => handleClick('4')}>4<\/button>\n <br \/>\n <button onClick={() => handleClick('5')}>5<\/button>\n <button onClick={() => handleClick('6')}>6<\/button>\n <button onClick={() => handleClick('7')}>7<\/button>\n <button onClick={() => handleClick('8')}>8<\/button>\n <br \/>\n <button onClick={() => handleClick('9')}>9<\/button>\n <button onClick={() => handleClick('0')}>0<\/button>\n <button onClick={() => handleClick('+')}>+<\/button>\n <button onClick={() => handleClick('-')}>-<\/button>\n <br \/>\n <button onClick={() => handleClick('*')}>*<\/button>\n <button onClick={() => handleClick('\/')}>\/<\/button>\n <button onClick={handleClear}>Clear<\/button>\n <button onClick={handleEqual}>=<\/button>\n <\/div>\n );\n}\n\nconst mapDispatchToProps = (dispatch) =>\n bindActionCreators({ addNumber, clear, equals }, dispatch);\n\nexport default connect(null, mapDispatchToProps)(Calculator);\n<\/code><\/pre>\nIn the Calculator<\/code> component, we are using the useState<\/code> hook to manage the input value. We have also defined three event handlers:<\/p>\n\nhandleClick<\/code>: This function appends the clicked value to the input string.<\/li>\nhandleClear<\/code>: This function clears the input string and calls the clear<\/code> action.<\/li>\nhandleEqual<\/code>: This function triggers the equals<\/code> action with the current input string.<\/li>\n<\/ul>\nWe are also mapping the addNumber<\/code>, clear<\/code>, and equals<\/code> actions to the component props using the mapDispatchToProps<\/code> function.<\/p>\nNow, let’s define the actions in the actions.js<\/code> file.<\/p>\nactions.js<\/code>:<\/p>\nexport const addNumber = (number) => {\n return {\n type: 'ADD_NUMBER',\n payload: number,\n };\n};\n\nexport const clear = () => {\n return {\n type: 'CLEAR',\n };\n};\n\nexport const equals = (input) => {\n return {\n type: 'EQUALS',\n payload: input,\n };\n};\n<\/code><\/pre>\nThe addNumber<\/code> action takes a number<\/code> argument and returns an action object with the ADD_NUMBER<\/code> type and the number as the payload.<\/p>\nThe clear<\/code> action does not take any arguments and returns an action object with the CLEAR<\/code> type.<\/p>\nThe equals<\/code> action takes an input<\/code> argument and returns an action object with the EQUALS<\/code> type and the input as the payload.<\/p>\nNext, let’s define the reducers in the reducers.js<\/code> file.<\/p>\nreducers.js<\/code>:<\/p>\nconst initialState = {\n history: [],\n result: 0,\n};\n\nconst calculatorReducer = (state = initialState, action) => {\n switch (action.type) {\n case 'ADD_NUMBER':\n return {\n ...state,\n result: Number(state.result + action.payload),\n };\n case 'CLEAR':\n return {\n ...state,\n result: 0,\n };\n case 'EQUALS':\n const result = eval(action.payload);\n return {\n ...state,\n history: [...state.history, action.payload + ' = ' + result],\n result: result,\n };\n default:\n return state;\n }\n};\n\nexport default calculatorReducer;\n<\/code><\/pre>\nThe calculatorReducer<\/code> function takes the state<\/code> and action<\/code> as inputs and returns the updated state based on the action type. In the case of the ADD_NUMBER<\/code> action, the result<\/code> is updated by adding the payload to the current result. In the case of the CLEAR<\/code> action, the result<\/code> is reset to 0. In the case of the EQUALS<\/code> action, the input is evaluated using the eval<\/code> function and the result is added to the history array.<\/p>\nFinally, let’s create the Redux store in the store.js<\/code> file.<\/p>\nstore.js<\/code>:<\/p>\nimport { createStore } from 'redux';\nimport calculatorReducer from '.\/reducers';\n\nconst store = createStore(calculatorReducer);\n\nexport default store;\n<\/code><\/pre>\nThe createStore<\/code> function from Redux is used to create the store by passing in the calculatorReducer<\/code> function.<\/p>\nDisplaying the Results<\/h2>\n
In the Calculator<\/code> component, let’s add a new section to display the previous calculations.<\/p>\nUpdate the Calculator<\/code> component with the following code:<\/p>\nfunction Calculator(props) {\n \/\/ ...\n\n return (\n <div>\n <input type=\"text\" value={input} disabled \/>\n <br \/>\n {\/* ... *\/}\n <br \/>\n <button onClick={handleClear}>Clear<\/button>\n <button onClick={handleEqual}>=<\/button>\n\n <br \/>\n <h3>History<\/h3>\n {props.history.map((item, index) => (\n <p key={index}>{item}<\/p>\n ))}\n <\/div>\n );\n}\n<\/code><\/pre>\nIn the JSX code, we have added a new heading element <h3><\/code> to display “History” and a mapping function to render each item of the history<\/code> array as a separate paragraph element <p><\/code>. The key<\/code> prop is set to the index<\/code> to provide a unique identifier for each item.<\/p>\nAlso, in the mapStateToProps<\/code> function in the Calculator.js<\/code> file, let’s add the following code:<\/p>\nconst mapStateToProps = (state) => {\n return {\n history: state.history,\n };\n};\n\nexport default connect(mapStateToProps, mapDispatchToProps)(Calculator);\n<\/code><\/pre>\nThe mapStateToProps<\/code> function maps the history<\/code> array from the state to the history<\/code> prop of the calculator component.<\/p>\nNow, when you run the app using npm start<\/code>, you should see the calculator interface with an input field to enter values and buttons to perform operations. The history panel will display the previous calculations.<\/p>\nRunning the App<\/h2>\n
To start the development server and run the app, open your terminal and run the following command in the project directory:<\/p>\n
npm start\n<\/code><\/pre>\nNow, the calculator app should be running on `http:\/\/localhost:3000`.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, you have learned how to build a simple calculator app using React and Redux. You have implemented the basic functionality of the calculator, including addition, subtraction, multiplication, and division. You have also added a history panel to display the previous calculations. By following this tutorial, you can further enhance the calculator app by adding more advanced operations or improving the user interface.<\/p>\n","protected":false},"excerpt":{"rendered":"
In this tutorial, we will be building a simple calculator app using React and Redux. The calculator will have basic functionality such as addition, subtraction, multiplication, and division. The app will also have a history panel to display the previous calculations. Prerequisites To follow along with this tutorial, it is Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[359,481,482,483,33,484,480,356],"yoast_head":"\nHow to Build a Calculator App with React and Redux - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n