Shubham Ankit

Shubham Ankit

1570523569

How to build Better React Forms with Formik

With the problem of form context solved with Formik, developers are free to focus on the behaviour they are aiming to achieve from their forms.
In this post, we’ll look at how we can build better React forms with Formik. Formik is a small library that helps you with the three major React form issues:

  1. Handling values in form state
  2. Validation and error messages
  3. Managing form submission

By fixing all of the above, Formik keeps things organized, thereby making testing, refactoring and reasoning about your forms a breeze. We’ll look at how Formik helps developers build better React forms while handling those three issues.

Installation

You can install Formik with NPM, Yarn or a good ol’ <script> via unpkg.com.

NPM

$ npm install formik --save	

YARN

 yarn add formik

Formik is compatible with React v15+ and works with ReactDOM and React Native.
You can also try before you buy with this demo of Formik on CodeSandbox.io

CDN

If you’re not using a module bundler or package manager, Formik also has a global (“UMD”) build hosted on the unpkg.com CDN. Simply add the following script tag to the bottom of your HTML file:

<script src="https://unpkg.com/formik/dist/formik.umd.production.js"></script>

Handling Values in Form State

Let’s look at how Formik handles one of the major React form issues of passing values around in React forms.

Consider an example where we have two input fields for email and password. We want to log the values of these fields to the console when the form is submitted. With the usual React form, we can create this form like so:

 import React, { Component } from 'react';
    class App extends Component {
    constructor(){
      super()
      this.state = {
        email: '',
        password: ''
      }
      this.handleEmailInput = this.handleEmailInput.bind(this)
      this.handlePasswordInput = this.handlePasswordInput.bind(this)
      this.logValues = this.logValues.bind(this)
    }
      logValues (){
        console.log(this.state.email);
        console.log(this.state.password);
      };
      handleEmailInput (e) {
        this.setState({ email: e.target.value });
      };
      handlePasswordInput (e) {
        this.setState({ password: e.target.value });
      };
      render() {
        return (
          <form onSubmit={this.logValues} >
            <input type="email" onChange={this.handleEmailInput}
	value={this.state.email}
	placeholder="Email"
            />    
            <input type="password" onChange={this.handlePasswordInput}
	value={this.state.password}
	placeholder="Password"
            />
            <button onClick={this.logValues}> Log Values </button>
          </form>
        );
      }
    }
    export default App;

Here, you’ll notice that we have a state object that manages the state of the form. We’ve also defined handlers to manage the state of the input fields, the values, the changes and so on. This is the conventional way of creating forms in React, so let’s skip all the explanations and get to the Formik part.

With Formik, this could be better, even neater and, oh, done with less code. Now let’s try recreating this exact functionality with Formik:

import React from 'react'
    import { withFormik, Form, Field } from 'formik'
    
      const App = ({
        values,
        handleSubmit,
      }) => (
        <Form>
          <Field type="email" name="email" placeholder="Email"/>
          <Field type="password" name="password" placeholder="Password"/>
          <button>Submit</button>
        </Form>
        )
      const FormikApp = withFormik({
        mapPropsToValues({ email, password}) {
          return {
            email: email || '',
            password: password || '',
          }
      },
        handleSubmit(values){
        console.log(values)
        }
      })(App)
      
    export default FormikApp;

Did you notice how clean and simple it was to recreate the form with Formik? Yeah, you did. Now, let’s walk you through it. Here, we used withFormik() to create the FormikApp component. WithFormik takes in an option, which, according to Formik docs, is a list of objects that we can pass into the withFormik() method to define its behavior.

In this case, we have passed in the mapPropsToValues({ }) option as a function which itself takes in the values of the input fields and passes them as props to our App component. In the App component we can access the values of all the input fields simply by destructuring it and passing in the Formik props called values, which is just an object with a bunch of key/value pairs.

With Formik, we don’t have to define an onChange handler or even an onSubmit on the form, it all comes built-in. All we have to do is import the Form prop from Formik and destructure it in the App component. With that done, we can use it to create our form fields.

Finally, with Formik, we don’t have to define a value in the input field. We simply import the Field prop provided by Formik and it saves us the stress of all those boilerplate codes.

Validation and Error Messages

In React, there is no simple way to handle validation in forms as at this time. Don’t get me wrong, there are good ways — just not as simple as Formik makes it. If you have created a sign-up form before in React, you’ll understand that you had to write your own validation logic to make sure users comply to your standards. You probably had to write a lot of code to validate the email input field, password, number, date and even your own error messages.

With Formik, we can use Yup to handle all that. It is so simple that you can implement standard validation in your input fields in less than 10 lines of code. That’s not all. It also allows you to define your custom error messages for every field condition you check.

Continuing from our last Formik form example, let’s validate the email and password fields with Yup:

import React from "react";
import { withFormik, Form, Field } from "formik";
import Yup from "yup";
      
      const App = ({ values, handleSubmit, errors, touched }) => (
      <Form>
        <div>
          {touched.email && errors.email && <p>{errors.email}</p>}
          <Field type="email" name="email" placeholder="Email" />
        </div>
        <div>
          {touched.password && errors.password && <p>{errors.password}</p>}
          <Field type="password" name="password" placeholder="Password" />
        </div>
        <button>Submit</button>
      </Form>
      );
      const FormikApp = withFormik({
        mapPropsToValues({ email, password }) {
          return {
          email: email || "",
          password: password || ""
        };
      },
      validationSchema: Yup.object().shape({
        email: Yup.string().email().required(),
        password: Yup.string().min(6).required()
      }),
      handleSubmit(values) {
        console.log(values);
      }
      })(App);
      export default FormikApp;

Here we have implemented validation and error reporting for both the email and password fields with the addition of about seven lines of code. How is this possible, you might ask? Well, let’s tell you how. In the FormikApp component, we passed in another option, validationSchema to withFormik({ }), which automatically handles all the validations for us.

With the errors prop we just destructured in the App component props, we now have access to the validationSchema errors. As a result, we can define a text field above the input fields to show the validation error messages to the users.

Finally, to be certain that the error messages appear only during submission (not when the user is typing), we used the touched prop. That way, we can conditionally check if a certain field has been touched. If it has, check if there are any errors; if there are, show the text when the field is submitted.

So far, if you run this App and try submitting false values, this is the output you’ll get:
This is image title

That is all well and good, but what if we wanted to provide a custom error message for the individual validation checks? With Formik, we can do this by specifying the messages inside the validationSchema methods like this:

validationSchema: Yup.object().shape({
        email: Yup.string()
          .email("Invalid Email !!")
          .required("Email is required"),
        password: Yup.string()
          .min(6, "Password must be above 6 characters")
          .required("Password is required")
      }),

At this point, the error messages will update appropriately with the contents that we have defined:
This is image title

Managing Form Submission

Formik gives us the functionality to make asynchronous requests even on submission of the form. Sometimes we’ll want to check if the submitted email address already exists in the database, and if it does we report it to the user.

Also, while the asynchronous request is running, we may want to dynamically disable the submit button until the execution completes. Formik provides us all this functionality and more. To further demonstrate this, let’s simulate a scene where, if an email address already exists, we’ll report an error to the user after the asynchronous request, which we have replaced with a timeout of two seconds. Then if the supplied email address doesn’t exist yet, we reset the form.

To do this, we’ll pass in the necessary Formik props as the second argument to the handleSubmit handler in our FormikApp component like this:

handleSubmit(values, {resetForm, setErrors, setSubmitting}) {
        setTimeout(() => {
          if (values.email === "john@doe.com") {
            setErrors({ email: 'Email already exists'})
          } else {
            resetForm()
          }
        },2000)
      }

Wonderful, now we can perform dynamic asynchronous operations while submitting forms. You may have noticed that we still have an unused argument setSubmitting, and you’re probably wondering why we have it there if we are not going to use it. Well, we are.

We’ll use it to conditionally disable our submit button when a submission operation is running. All we need to do is access a prop that is passed to our App component called isSubmitting. As the name suggests, it is a Boolean. If we are submitting, the value is true so we can do something, and if we are not, it’s false, and we can do something else.

const App = ({ values, handleSubmit, errors, touched, isSubmitting }) => (
      <Form>
        <div>
          {touched.email && errors.email && <p>{errors.email}</p>}
          <Field type="email" name="email" placeholder="Email" />
        </div>
        <div>
          {touched.password && errors.password && <p>{errors.password}</p>}
          <Field type="password" name="password" placeholder="Password" />
        </div>
          <button disabled={isSubmitting}>Submit</button>
      </Form>
      );

Then in the handleSubmit handler, we just set setSubmitting to false:

handleSubmit(values, {resetForm, setErrors, setSubmitting}) {
        setTimeout(() =>{
          if (values.email === "john@doe.com") {
          setErrors({ email: 'Email already exists'})
        } else {
        resetForm()
        }
        setSubmitting(false)
        },2000)
      }

Now whenever a submit operation is running, the submit button is conditionally disabled until the asynchronous operation is done executing.

Conclusion

This is Formik at the barest minimum. There are a ton of things you can do with Formik that we didn’t touch in this post. You can go ahead and find out more yourself in the documentation and see how you can optimize the React forms in your existing application or how to implement these amazing features in your subsequent React apps. Compared to the conventional way of creating forms in React, Formik is a must have.

Learn More

#reactjs #javascript

What is GEEK

Buddha Community

How to build Better React Forms with Formik

Anil Verma

1570862424

Great article Shubham, Even the React official documentation site mentions Formic as one solution for creating forms in Creat. However I would highly recommend developers understand the concept of controlled components and uncontrolled components.
I have taken a stab at it in one of my blog posts. https://www.ojblabs.com/react-form/

Thanks

Autumn  Blick

Autumn Blick

1598839687

How native is React Native? | React Native vs Native App Development

If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?

In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.

A brief introduction to React Native

Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.

React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.

Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.

Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.

The popularity of React Native comes from its advantages. Some of its advantages are as follows:

  • Performance: It delivers optimal performance.
  • Cross-platform development: You can develop both Android and iOS apps with it. The reuse of code expedites development and reduces costs.
  • UI design: React Native enables you to design simple and responsive UI for your mobile app.
  • 3rd party plugins: This framework supports 3rd party plugins.
  • Developer community: A vibrant community of developers support React Native.

Why React Native is fundamentally different from earlier hybrid frameworks

Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.

React Native is very close to native. Consider the following aspects as described on the React Native website:

  • Access to many native platforms features: The primitives of React Native render to native platform UI. This means that your React Native app will use many native platform APIs as native apps would do.
  • Near-native user experience: React Native provides several native components, and these are platform agnostic.
  • The ease of accessing native APIs: React Native uses a declarative UI paradigm. This enables React Native to interact easily with native platform APIs since React Native wraps existing native code.

Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.

#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native

Hayden Slater

1599277908

Validating React Forms With React-Hook-Form

Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long. This is can be easily done using React Hook From. In this article, I will show you how.

Required Fields

The most simple, yet very common, validation is to make sure that an input component contains input from the user. React Hook Form basic concept is to register input tags to the form by passing register() to the tag’s ref attribute. As we can see here:

#react-native #react #react-hook-form #react-hook

Franz  Becker

Franz Becker

1651604400

React Starter Kit: Build Web Apps with React, Relay and GraphQL.

React Starter Kit — "isomorphic" web app boilerplate   

React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Express, GraphQL and React, containing modern web development tools such as Webpack, Babel and Browsersync. Helping you to stay productive following the best practices. A solid starting point for both professionals and newcomers to the industry.

See getting started guide, demo, docs, roadmap  |  Join #react-starter-kit chat room on Gitter  |  Visit our sponsors:

 

Hiring

Getting Started

Customization

The master branch of React Starter Kit doesn't include a Flux implementation or any other advanced integrations. Nevertheless, we have some integrations available to you in feature branches that you can use either as a reference or merge into your project:

You can see status of most reasonable merge combination as PRs labeled as TRACKING

If you think that any of these features should be on master, or vice versa, some features should removed from the master branch, please let us know. We love your feedback!

Comparison

 

React Starter Kit

React Static Boilerplate

ASP.NET Core Starter Kit

App typeIsomorphic (universal)Single-page applicationSingle-page application
Frontend
LanguageJavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)JavaScript (ES2015+, JSX)
LibrariesReact, History, Universal RouterReact, History, ReduxReact, History, Redux
RoutesImperative (functional)DeclarativeDeclarative, cross-stack
Backend
LanguageJavaScript (ES2015+, JSX)n/aC#, F#
LibrariesNode.js, Express, Sequelize,
GraphQL
n/aASP.NET Core, EF Core,
ASP.NET Identity
SSRYesn/an/a
Data APIGraphQLn/aWeb API

Backers

♥ React Starter Kit? Help us keep it alive by donating funds to cover project expenses via OpenCollective or Bountysource!

lehneres Tarkan Anlar Morten Olsen Adam David Ernst Zane Hitchcox  

How to Contribute

Anyone and everyone is welcome to contribute to this project. The best way to start is by checking our open issues, submit a new issue or feature request, participate in discussions, upvote or downvote the issues you like or dislike, send pull requests.

Learn More

Related Projects

  • GraphQL Starter Kit — Boilerplate for building data APIs with Node.js, JavaScript (via Babel) and GraphQL
  • Membership Database — SQL schema boilerplate for user accounts, profiles, roles, and auth claims
  • Babel Starter Kit — Boilerplate for authoring JavaScript/React.js libraries

Support

License

Copyright © 2014-present Kriasoft, LLC. This source code is licensed under the MIT license found in the LICENSE.txt file. The documentation to the project is licensed under the CC BY-SA 4.0 license.


Author: kriasoft
Source Code: https://github.com/kriasoft/react-starter-kit
License: MIT License

#graphql #react 

Seamus  Quitzon

Seamus Quitzon

1598954760

Build a Contact Form with React Hooks and PHP

A while ago I wrote an article about creating a contact form using React and PHP. Many people found it interesting. So, here I am writing an updated version of that article.

Check out the article about creating a contact form with React and PHP:

Hooks are a new addition in React and we are going to re-create the contact form using React Hooks.

Prerequisites? Not really!

Same as the previous project. This tutorial is beginners friendly. You don’t have to be an expert in Javascript, React, or PHP but I won’t go into basic details like installing React and setting up the project.

I assume you already have an up and running React project. We will focus on creating the component.

Creating the component

If you have a component folder in your project please go ahead and create a ‘Form’ folder inside it. It is up to you to decide where the component should live. Once you created the folder let’s create the ‘index.js’ file.

#react #reactphp #react-php-contac-form #contact-form #react-hook

Aubrey  Price

Aubrey Price

1589722410

Build a simple React Native Pokemon app with React-Navigation

As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology. So, let’s build this simple app.
For this app, we will be using PokeApi to get our pokemon data, and also we will be using Hooks. I am using pokemondb for pokemon sprites. It’s just a personal preference you can use whatever you want.

#react-native #react-native-app #react-navigation #react-native-development #react