Form Validation using Formik Yup and Material UI

Formik, Yup and Material UI

Form Validation with Formik, Yup and Material UI all together. How to Validate form in Material UI with Formik. Easy and simple way of using Formik Yup and Material UI. TextField Validation with Formik Yup and Material UI wiht practical example.
import React, {useState} from ‘react’
import Button from “@material-ui/core/Button”;
import {Formik, Form, Field, ErrorMessage} from “formik”;
import {TextField} from “formik-material-ui”;
import * as Yup from “yup”;
function Contact() {
   const [data, setData]=useState({})
   const initialValues={
     name: “”,
     email: “”,
     subject: “”,
     message: “”
   }
   const onSubmit =(values, onSubmitProps)=>{
     onSubmitProps.setSubmitting(false)
     onSubmitProps.resetForm()
     setData(values)
   }
   const validationSchema= Yup.object({
     email: Yup.string().email().required(“Email Required”)
   })
   const {name}=data;
    return (
      <div>
        <Formik
        initialValues={initialValues}
        onSubmit={onSubmit}
        validationSchema={validationSchema}
        >
          {formik=>{
            return(
              <Form>
                <br/>
                <div>
                <div align=”center” className=”container contactdiv”>
              <div  className=”form-control-lg”>
                <Field
                name=”email”
                type=”email”
                id=”email”
                label=”Email”
                component={TextField}
                />
              </div>
              <br/>
              <div >
                <Button
                variant=”outlined”
                color=”primary”
                size=”large”
                type=”submit”
                disabled={!(formik.dirty && formik.isValid) || formik.isSubmitting}
                >
                Submit
                </Button>
                <br/>
              </div>
                </div>
              <br/>
              </div>
              </Form>
            )
          }}
        </Formik>
        </div>
    )
}
export default Contact

ReactJS Component Introduction

Component

A Component is the building blocks of React. React App is made up of pieces called components. Components make the task of building User Interfaces much easier. You can see a User Interface broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final User Interface.

In React there are two types of components:

Functional Components:

Functional components are simply JavaScript functions. We can create a functional component in React by writing a JavaScript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React:

function functionalComponent()

{

return <h1>Welcome Message!</h1>;

}

Class Components:

The class components are little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React. Below example shows a valid class-based component in React:

class classComponent extends React.Component

{

render(){ return <h1>Welcome Message!</h1>;

}

}

Functional component used only when we are sure that our component does not require to interact or work with any other component. That is, these components do not require data from other components however we can compose multiple functional components under a single functional component. We can also use class-based components for this purpose but it is not recommended as using class-based components without need will make your application in-efficient.

In this post, we will mainly write functional components to make things easier to understand. We will discuss class-based components in detail later in the tutorial.

 

Component Constructor

If there is a constructor() function in your component, this function will be called when the component gets initiated.

The constructor function is where you initiate the component’s properties.

In React, component properties should be kept in an object called state.

You will learn more about state later in this tutorial.

The constructor function is also where you honor the inheritance of the parent component by including the super() statement, which executes the parent component’s constructor function, and your component has access to all the functions of the parent component (React.Component).

Example

Create a constructor function in the Car component, and add a color property:

class Car extends React.Component {
  constructor() {
    super();
    this.state = {color: "red"};
  }
  render() {
    return <h2>I am a Car!</h2>;
  }
}

Props

Another way of handling component properties is by using props. Props are like function arguments, and you send them into the component as attributes.

Example

Use an attribute to pass a color to the Car component, and use it in the render() function:

class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.color} Car!</h2>;
  }
}

ReactDOM.render(<Car color="red"/>, document.getElementById('root'));


Components in Components

We can refer to components inside other components:

Example

Use the Car component inside the Garage component:

class Car extends React.Component {
  render() {
    return <h2>I am a Car!</h2>;
  }
}

class Garage extends React.Component {
  render() {
    return (
      <div>
      <h1>Who lives in my Garage?</h1>
      <Car />
      </div>
    );
  }
}

ReactDOM.render(<Garage />, document.getElementById('root'));

What is JSX – Introduction to JSX

What is JSX

JSX looks like HTMl but in reality its not HTML at all. React uses JSX for templating instead of regular JavaScript. Basically, by using JSX you can write concise HTML/XML-like structures (e.g., DOM like tree structures) in the same file as you write JavaScript code, then Babel will transform these expressions into actual JavaScript code. Unlike the past, instead of putting JavaScript into HTML, JSX allows us to put HTML into JavaScript.

Why JSX is used ?

JSX is faster because it performs optimization while compiling code to JavaScript.

JSX is also type-safe and most of the errors can be caught during compilation.

JSX makes it easier and faster to write templates, if you are familiar with HTML.

 

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.

JavaScript expressions in JSX

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

JavaScript expressions in JSX

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

 

import React from ‘react’;

import ReactDOM from ‘react-dom’;

var name = “JSX”;

var element = <h1>Hello this is { name } < /h1>;

ReactDOM.render(

    element,

    document.getElementById(“root”)

);