Blogging my journey of learning Full stack devlopment and creating an App to get a hands on knowledge.

Search This Blog

Tuesday, 31 January 2023

Add a Yup validation Schema to the react form using MUI as a UI component

React Hook Form is a React library that is used to make performant, flexible, and extensible forms with easy-to-use validation support.

Dependencies

npm i react-hook-form


Pass the rules to the React Hook Form useForm() function using yupResolver() function

Then inside your component, you can use the hook:

const {
        register,
        control,
        handleSubmit,
        formState: { errors }
    } = useForm({
        mode :'onTouched',
        resolver: yupResolver(formValidationSchema)
    });

The useForm hook takes and returns two objects containing few properties:

mode : It can be passed to useForm hook if you want to validate the field whenever there is an onChange event for example. the possible values are onChange, onBlur, onSubmit, onTouched, all. With onSubmit being the default value

resolver : This function allows you to use any external validation library such as Yup and many others

register : is a function to be assigned to each input field ref so that React Hook Form can track the changes for the input field value

handleSubmit  : is the function that is called when the form is submitted

errors : is an object that will contain the validation errors of each input if any

control: register components, work with Controller (wrapper component for controlled inputs)


Define a MUI textField for which you want to do validation and a error under it.

 <TextField sx={{
                  bgcolor: 'white',
                }}
            required
            id="invoiceID"
            name="invoiceID"
            fullWidth
            margin="dense"
            size="small"
            {...register('invoiceID')}
            error={errors.invoiceID ? true : false}
            onChange={(e) => handleHeaderInputChange(e)}
/>
<Typography color="error" sx={{ fontSize: '10px' }}>
   {errors.invoiceID?.message}
</Typography>

We register form fields with the React Hook Form by calling the register function above with the field name of input element {...register('fieldname')}.

If error object contains the invoiceID field, the error message will be displayed.


Define the yup validation schema

Dependencies

npm i yup


    invoiceID: Yup.number()
    .transform((_, val) => (val !== "" ? Number(val) : null))
    .nullable()
    .required('Invoice ID number is required'),

Since I have defined the mode to onTouched in react useForm hook ,form will also be validated whenever there is click on the Textfield along with its default validation on Submit



Read More

Monday, 30 January 2023

How to Add Date picker field in your react form using MUI

 The DatePicker component let the user select a date, from the dropdown

Dependencies

npm install @mui/x-date-pickers/AdapterDayjs

npm install @mui/x-date-pickers/LocalizationProvider

npm install @mui/x-date-pickers/DatePicker


The date picker is rendered as a modal dialog on mobile, and a textbox with a popup on desktop.

<LocalizationProvider id dateAdapter={AdapterDayjs}>
    <Controller name="issueDate"
                control={control}
                defaultValue={null}
                render={({
                          fieldState: { invalid }
                        }) => (
                             <DatePicker
                                disableFuture
                                openTo="year"
                                views={['year', 'month', 'day']}
                                value={formData.invoiceData.issueDate}
                                onChange={(e) => handleHeaderInputChange(e,"issueDate"
)}
                                 renderInput={(params) =>
                                            <TextField {...params}
                                                       error={invalid}
                                                       sx={{ bgcolor: 'white'}}
                                                       size="small" />}
                                  />
                                  )}
      />
</LocalizationProvider>


LocalizationProvider : Use LocalizationProvider to change the date-library locale that is used to render pickers. It uses prop dateAdapter to pass which date management library it should use. Here we have used AdapterDayjs.

Controller : In order to control MUI Text Field, React Hook Form uses Controller, which can easily integrate with any third-party-controlled UI components. Controller component  wrapper allows you to register a controlled external component, similar to how the register method works. In this case, instead of the register method, you will use the control object from the useForm Hook.

DatePicker : In DatePicker you pass the TextField  in renderInput props.



Read More

How to convert String representation of Date to your Local Date Format in JavaScript React

You can convert the date string based on your current locations format by using following ways by using Date object.


Date.prototype.toLocaleDateString()

Syntax: 

toLocaleDateString()
toLocaleDateString(locales)

Example:

toLocaleDateString()

var date = new Date(e);
//e is an event with value on Jan 30 2023 00:00:00 GMT-0600 (Central Standard Time)
date.toLocaleDateString();
//Output : 1/30/2023

toLocaleDateString(locales): In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument

var date = new Date(e);
//e is an event with value on Jan 30 2023 00:00:00 GMT-0600 (Central Standard Time)
date.toLocaleDateString("en-GB");
//Output : 30/01/2023 format that British English uses day-month-year order
Read More

How to Create Pie Chart in React

 Create a Custom Pie Chart with your data using Chart from https://www.chartjs.org/

Dependencies

npm i react-chartjs-2

npm i chart.js

npm install @mui/material 

Add the details for your Pie Chart which will be passed in the <PieChart> component

Label: label of your pie chart

Data: Pass the data you want to display(I created a separate file that contains array of Data in JSON format and exported it to be used in this file as InvoiceData)

export const numofInvoiceData = {
    labels: InvoiceData.map((invoice) => invoice.status),
    datasets: [
        {
            label: 'Invoice Amounts ',
            data: InvoiceData.map((invoice) => invoice.invoiceCount),
            backgroundColor: [
                'rgba(253, 172, 96)',
                'rgba(253, 96, 96)',
                'rgba(96, 253, 253)'
            ],
            borderColor: [
                'rgba(253, 172, 96)',
                'rgba(253, 96, 96)',
                'rgba(96, 253, 253)'
            ],
            borderWidth: 1,
        },
    ],
};
{.....}

<PieChart data={numofInvoiceData} />

Create a PieChart Component and add your props data in Pie component.

import React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Pie } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);


export default function PieChart({data}) {
  return <Pie data={data} />;
}

Checkout the full code implementation at 

Invoice Portal

Read More

Saturday, 28 January 2023

How to create Navigation Bar component in React using MUI

Create a new file and name it as NavigationBar and call it in your application as a static component.

MUI has many examples and ways in which you can render the navigation content and actions related to the current screen

Dependencies:

npm i react-router-dom

npm install @mui/material @mui/icons-material


For large screen device


For  small screen device


1.Create AppBar  Component and make it static ,so it remains static at Top of screen

    <AppBar position="static">

2.Created a Logo and added it in <Link> ,so that when clicked it will take you back to Home Page

3.Declared a Menu Item Name in a variable and called it in 

<Menu id="menu-appbar"
{.....Code }
       {pages.map((page) => (
          <MenuItem key={page.menuLinkName} onClick={handleCloseNavMenu}>
              <ReactLink to={page.menuLinkName}  style={{textDecoration:'none'}}>
<Typography textAlign="center">{page.menuName}</Typography>
</ReactLink>
          </MenuItem>

4.Used ReactLink from react-router-dom module ,for routing to other component when clicked.

5.Declared two states

 const [anchorElNav, setAnchorElNav] = React.useState(null);

    const [anchorElUser, setAnchorElUser] = React.useState(null);

where handleOpenNavMenu sets a event for Onclick event and , handleCloseNavMenu reloads it for Small screen UI.

And handleOpenUserMenu sets a event for Onclick event and , handleCloseUserMenu reloads it for Large screen UI.

Git Repo Link: https://github.com/anjutus/invoice-portal

Read More

Monday, 16 January 2023

Design and Prototype of Invoice Portal in Figma


A project needs a visualization of what it needs ,feels and looks like. Designing and Prototyping it is makes your UI and functional requirements quite clear if you do it in beginning of your project before Code phase. I used Figma for designing and prototyping of Invoice Portal.

Following are the UI of my Invoice Portal

Suppliers Dashboard


Supplier view Invoice list


Supplier create Invoice 


Buyer View Invoice list


Buyer View Pending Invoice


Buyer view Invoice


Buyers Download Invoice





Read More

Sunday, 15 January 2023

Featured Post

Invoice Portal Project Links

Web App link for Invoice Portal  Invoice Portal App lets an user view and create an Invoice. Features: View the list of Number of Invoices b...

Powered by Blogger.

Popular Posts