We now have a youtube channel. Subscribe!

ReactJS | Add Expense (Example)

ReactJS | Add Expense


Hello folks! welcome back to a new section of our tutorial on ReactJS. In this section of our tutorial on ReactJS, we will be studying about how to add expenses to our ReactJS application.

Open up ExpenseEntryItemList.js and import connect from redux library.

import { connect } from 'react-redux';

Next, import Formik library.

iimport { Formik } from 'formik';

Next, import WithRouter method from router library.

import { withRouter } from "react-router-dom";

Next, import addExpense from action library.

import { addExpense } from '../actions/expenseActions';

Next, create a constructor with initial values for expenses.

constructor(props) {
   super(props); 
   this.initialValues = { name: '', amount: '', spend_date: '', category: '' } 
}

Next, write the validate method.

validate = (values) => {
   const errors = {};
   if (!values.name) {
      errors.name = 'Required';
   }
   if (!values.amount) {
      errors.amount = 'Required';
   }
   if (!values.spend_date) {
      errors.spend_date = 'Required';
   }
   if (!values.category) {
      errors.category = 'Required';
   }
   return errors;
}

Next, add event handler method.

handleSubmit = (values, setSubmitting) =< {
   setTimeout(() =< {
      let newItem = {
         name: values.name,
         amount: values.amount,
         spendDate: values.spend_date,
         category: values.category
      }
      this.props.addExpense(newItem);
      setSubmitting(false);
      this.props.history.push("/list");
   }, 400);
}

Here,

  • Used addExpense method to add expense item.
  • Used router history method to move to expense list page.

Next, update the render method with form created using Formik library.

render() {
   return (
      <div id="expenseForm">
         <Formik
            initialValues={this.initialValues}
            validate={values => this.validate(values)}
            onSubmit={(values, { setSubmitting }) => this.handleSubmit(values, setSubmitting)}>
            {
               ({
                  values,
                  errors,
                  touched,
                  handleChange,
                  handleBlur,
                  handleSubmit,
                  isSubmitting,
                  /* and other goodies */
               }) => (
                  <form onSubmit={handleSubmit}>
                     <label for="name">Title <span>{errors.name && touched.name && errors.name}</span></label>
                     <input type="text" id="name" name="name" placeholder="Enter expense title"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.name} />

                     <label for="amount">Amount <span>{errors.amount && touched.amount && errors.amount}</span></label>
                     <input type="number" id="amount" name="amount" placeholder="Enter expense amount"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.amount} />

                     <label for="spend_date">Spend Date <span>{errors.spend_date && touched.spend_date && errors.spend_date}</span></label>
                     <input type="date" id="spend_date" name="spend_date" placeholder="Enter date"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.spend_date} />

                     <label for="category">Category <span>{errors.category && touched.category && errors.category}</span></label>
                     <select id="category" name="category"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.category}>
                        <option value="">Select</option>
                        <option value="Food">Food</option>
                        <option value="Entertainment">Entertainment</option>
                        <option value="Academic">Academic</option>
                     </select>
                     <input type="submit" value="Submit" disabled={isSubmitting} />
                  </form>
               )
            }
         </Formik>
      </div>
   )
}


Next, map dispatch method to component properties.

const mapDispatchToProps = { 
   addExpense, 
};

Finally, connect the component to store and also wrap the component with WithRouter to get programmatic access to router links.

export default withRouter(connect(
   null,
   mapDispatchToProps
)(ExpenseEntryItemForm));

The complete code of the component is as follows -

import React from "react";

import { connect } from 'react-redux';
import { Formik } from 'formik';
import { withRouter } from "react-router-dom";
import { addExpense } from '../actions/expenseActions';

class ExpenseEntryItemForm extends React.Component {
   constructor(props) {
      super(props);

      this.initialValues = { name: '', amount: '', spend_date: '', category: '' }
   }
   validate = (values) => {
      const errors = {};
      if (!values.name) {
         errors.name = 'Required';
      }
      if (!values.amount) {
         errors.amount = 'Required';
      }
      if (!values.spend_date) {
         errors.spend_date = 'Required';
      }
      if (!values.category) {
         errors.category = 'Required';
      }
      return errors;
   }
   handleSubmit = (values, setSubmitting) => {
      setTimeout(() => {
         let newItem = {
            name: values.name,
            amount: values.amount,
            spendDate: values.spend_date,
            category: values.category
         }
         this.props.addExpense(newItem);
         setSubmitting(false);
         this.props.history.push("/list");
      }, 400);
   }
   render() {
      return (
         <div id="expenseForm">
            <Formik
               initialValues={this.initialValues}
               validate={values => this.validate(values)}
               onSubmit={(values, { setSubmitting }) => this.handleSubmit(values, setSubmitting)}>
               {
                  ({
                     values,
                     errors,
                     touched,
                     handleChange,
                     handleBlur,
                     handleSubmit,
                     isSubmitting,
                     /* and other goodies */
                  }) => (
                     <form onSubmit={handleSubmit}>
                        <label for="name">Title <span>{errors.name && touched.name && errors.name}</span></label>
                        <input type="text" id="name" name="name" placeholder="Enter expense title"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.name} />

                        <label for="amount">Amount <span>{errors.amount && touched.amount && errors.amount}</span></label>
                        <input type="number" id="amount" name="amount" placeholder="Enter expense amount"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.amount} />

                        <label for="spend_date">Spend Date <span>{errors.spend_date && touched.spend_date && errors.spend_date}</span></label>
                        <input type="date" id="spend_date" name="spend_date" placeholder="Enter date"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.spend_date} />

                        <label for="category">Category <span>{errors.category && touched.category && errors.category}</span></label>
                        <select id="category" name="category"
                           onChange={handleChange}
                           onBlur={handleBlur}
                           value={values.category}>
                           <option value="">Select</option>
                           <option value="Food">Food</option>
                           <option value="Entertainment">Entertainment</option>
                           <option value="Academic">Academic</option>
                        </select>
                        <input type="submit" value="Submit" disabled={isSubmitting} />
                     </form>
                  )
               }
            </Formik>
         </div>
      )
   }
}
const mapDispatchToProps = {
   addExpense,
};
export default withRouter(connect(
   null,
   mapDispatchToProps
)(ExpenseEntryItemForm));

Next, serve the application making use of npm command.

npm start

Next, open the web browser and then enter http://localhost:3000 in the address bar and press enter.

List_expenses


Alright guys! This is where we are going to be rounding up for this tutorial. In our next tutorial post, we will be introducing Node.js to you guys.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2022 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain