<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abdi Cagarweyne on Medium]]></title>
        <description><![CDATA[Stories by Abdi Cagarweyne on Medium]]></description>
        <link>https://medium.com/@a.cagarweyne?source=rss-6266e3b75525------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1hHVL8OKGDV-1LA-a24zsQ.jpeg</url>
            <title>Stories by Abdi Cagarweyne on Medium</title>
            <link>https://medium.com/@a.cagarweyne?source=rss-6266e3b75525------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:01:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.cagarweyne/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamic React Form with Formik]]></title>
            <link>https://medium.com/@a.cagarweyne/dynamic-react-form-with-formik-4aad80ad7e5?source=rss-6266e3b75525------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aad80ad7e5</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[formik]]></category>
            <dc:creator><![CDATA[Abdi Cagarweyne]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 20:29:28 GMT</pubDate>
            <atom:updated>2018-12-01T21:02:51.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*Z4vnPwCTqgINjb__UeOBgQ.png" /><figcaption>React loves Formik</figcaption></figure><p>React has certainly made Front End development a whole lot more pleasant and has simplified a lot of complex things. Even though React makes developing client side a whole lot easier than before, creating robust forms that stand up to the needs of modern apps can be really difficult and complex.</p><p>Creating forms in React is actually pretty simple, where the pain points arise is when you need to have validation, error messages and you need to have more than one form. Using just the simple controlled form components quickly becomes verbose, repetitive and very cumbersome. In general, creating forms with React can be quite challenging!</p><p>There are some really good libraries out there which try to make handling forms a whole lot easier like Redux-form. While this library certainly has its uses, it would be an overkill for simple apps and running each form change through the redux store can really impact performance as your app scales.</p><p>There is one React form library that is fast becoming the standard for React forms and one that has a bright future in the React ecosystem. In fact, it is recommended on the React forms page right at the bottom of the page, and it’s called <a href="https://jaredpalmer.com/formik/docs/api/formik">Formik</a>.</p><p>Formik is a set of React components that utilizes the React render method concept. Formik’s motto is: “React forms without the tears!” And I’m sure after discovering Formik you will not have any tears when it comes to forms in React!</p><p>What I really love about Formik is that it is just a React component and nothing else. So, it doesn’t use any fancy or complex framework internally and it’s footprint is really small, which means that it won’t bloat your codebase. One of the creators of Formik <a href="https://twitter.com/jaredpalmer">Jared Palmer</a> did an excellent talk recently on Formik and how it came about.</p><p>In the talk he demonstrated how Formik works by building a mini version. I highly recommend that you watch his talk <a href="https://www.youtube.com/watch?v=oiNtnehlaTo">here</a>. In the next part we will go through how to create a mini formik component to better understand how we can abstract out the mundane tasks of handling forms in React in an elegant way using only React.</p><h3>MiniFormik</h3><p>Let’s now create a mini version of Formik so that we can better understand how it works under the hood. Jared did a great job in explaining how the first version of Formik was created in his talk in Alicante, Spain, and this explanation is based on that React talk.</p><p>When creating forms in React we typically make use of a few things, React state, a handleChange function and a handleSubmit function that is called when we want to submit the form. We will take the official React docs form example for handling multiple inputs (<a href="https://reactjs.org/docs/forms.html">https://reactjs.org/docs/forms.html</a>), the example uses a reservation component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa6a41129ba0b18f0832b66e579549b2/href">https://medium.com/media/fa6a41129ba0b18f0832b66e579549b2/href</a></iframe><p>This is a simple form component that uses the computed property value syntax to update the state, so instead of having multiple change handlers, we can use just use one handler and let it choose what to do based on the value of event.target.value.</p><p>In the reservation example above, we have two inputs with the names isGoing and numberOfGuests Then in the state we initialize the same values isGoing: true, numberOfGuests: 2.</p><p>So, when the handleChange is called we pull off the name part of event object and set the key as the name and the value from the event object. This is handy and allows us to use just the one function to handle multiple<br>change events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/0*UXpdU12HaTV2j4lA.png" /></figure><p>This is a simple form where there is only two inputs, without validation and error messages. You can see that there is quite a lot of boilerplate code and if we were to add validation and error messages into the mix then things can get quite messy very quickly.</p><p>Let’s now abstract out the state and the handleChange function into a separate component and then expose state and the handle change to the reservation component via props. For this we will make use of the render props pattern, if you are not familiar with this concept then I highly recommend you read Michael Jackson’s use a render prop tutorial <a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce">here</a></p><p>Let’s now extract out the state and the handleChange function from the reservation component and create a new component called<br>MiniFormik:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3a57d4372ec5fba1ba0e0fa1e339627/href">https://medium.com/media/f3a57d4372ec5fba1ba0e0fa1e339627/href</a></iframe><p>We’ve simply extracted out the state and the handleChange function from the reservation component. You will notice that we are using theevent.persist() function and this to let us target the correct event data since setState is Asynchronous.</p><p>In the render method we are returning the children that are passed in and calling it with the state and the handleChange callback function. Let’s now refactor the reservation component to make use of our MiniFormik render prop component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f799702b7bfef0889e9831a4e3109b/href">https://medium.com/media/b1f799702b7bfef0889e9831a4e3109b/href</a></iframe><p>The form works exactly as before, only this time we have extracted out the handleChange and the state values into a separate component, for us to now make this form reusable on any type of data we need to make a few changes, in particular the values that we want to initialize the form with and pass in our own handleSubmit function that will be called once the submit button is clicked. Let’s make those changes now to our MiniFormik component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c10033d098aff3f5f47d1f3ac9b1ecb/href">https://medium.com/media/0c10033d098aff3f5f47d1f3ac9b1ecb/href</a></iframe><p>We can now initialize the form with our own values by passing an initialValues prop and we can also pass our own onSubmit function that will be called with the form values once the submit button is clicked. Let&#39;s see how this works with our reservation component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d26e4e6359f8645b1d8a65d12eac26/href">https://medium.com/media/a9d26e4e6359f8645b1d8a65d12eac26/href</a></iframe><p>Now we don’t have hardcoded state values inside the MiniFormik component, we simply pass in the initial values ourselves then pull off the values object from the props and update the values for the input by preceding it with values. We also pass in the onSubmit prop that will be called once the form is submitted.</p><p>So we can actually now reuse this form as much as we want without having to duplicate the logic of keeping the form state and and the handleChange function in another component that needs to capture data.</p><p>We can go further, let’s say that we want add a handle blur function that will be called when any of the fields are visited by the user. We can do this easily by adding a handleBlur function to the MiniFormik component and then passing this down:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f47f6e3acbc9067d052977120930d677/href">https://medium.com/media/f47f6e3acbc9067d052977120930d677/href</a></iframe><p>To add a handleBlur function, we have simply refactored our handleChange function to update the state whenever the user touches any of the fields. So, it updates the touched object with field that is visited by the user by adding that fields name as the key into the object and setting its value to true to signify that this field has been touched by the user.</p><p>We then pass the handleBlur function down to the child component in the render. This lets us use the handleBlur function inside our Reservation component by pulling it off the props object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5df8b92a78e79cf58beab4f05dcd4c2/href">https://medium.com/media/f5df8b92a78e79cf58beab4f05dcd4c2/href</a></iframe><p>As you can see we can extend the MiniFormik form as we want, we can also add an errors object into our state and then run validations against the values that are entered by the user, and whenever there is invalid input we simply update the errors object with the name of the field that has the error. This allows us to use the errors object to give validation messages to the user.</p><p>You can now see that we have been able to create a render prop component that will handle all of the form aspects of our react app. This was a simple demonstration of how the Formik component abstracts away the mundane tasks of forms in React and it doesn’t actually use any fancy algorithms or complex libraries — it’s just React.</p><p>However, Formik covers a lot of different edge cases and is more robust than our simple example here. Now that we have a better understanding of how Formik works, let’s actually use Formik to see how easy it is to create forms in React.</p><h3>Formik</h3><p>There are a few different components that you can use to handle forms with Formik, the first one that we will examine is the Formik component. This is a component that uses the render props pattern, and it is the full version of the MiniFormik that we created, only this time it comes with the ability to do lots more!</p><p>Formik gives you many tools and options to render a form. When using the Formik render prop component you can render a form with it in three different ways:</p><ol><li>Passing a component to the component prop of Formik</li><li>Using the render method and passing your forms markup in JSX</li><li>Wrap your form with Formik and add your form as JSX</li></ol><h3>Using a component</h3><p>We will look at the three ways in more detail starting with the first method: passing a component to Formik via its component prop. We’ll use the component example given in the docs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57c6d638226f1f67a63e4d07397c5129/href">https://medium.com/media/57c6d638226f1f67a63e4d07397c5129/href</a></iframe><p>A simple form component that has a single input field, it gets the values, errors, submit, blur and change functions via its props that must be passed down. Next we will simply pass the ContacForm component as the value to the component prop on Formik and it will inject the required props:</p><pre>&lt;Formik component={ContactForm} /&gt;;</pre><h3>Using the render method</h3><p>The second way that you can render a form with Formik is using the render pattern, and this is similar to the previous method, but this allows you to use the render prop of Formik and pass it your form’s raw JSX markup or a component that you have imported:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4011fd129b11766e8f5a4b834a573da/href">https://medium.com/media/f4011fd129b11766e8f5a4b834a573da/href</a></iframe><h3>Render as children</h3><p>Finally, you can render your form as children of the Formik component, this is similar to our MiniFormik implementation that we created earlier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef2a27abbd762823431d44e3c600d202/href">https://medium.com/media/ef2a27abbd762823431d44e3c600d202/href</a></iframe><p>Note: you can also use the children prop and pass it your forms raw markup:</p><pre>&lt;Formik children={props =&gt; &lt;ContactForm {...props} /&gt;} /&gt;</pre><p>So as you can see it’s pretty simple to render a form with Formik, in fact the steps are very similar to how you would create a form using just React — but the beauty of it is that the form is in React only and there is no other library that is being used under the hood.</p><p>These examples are very simple and are only scratching the surface, but where Formik really earns its stars is in the props that are made available to you and how you can use them to create all sorts of different and complex forms. Let’s dig in and explore the props that are made available to us and see how we can create a dynamic form with Formik.</p><h3>Formik use case — Dynamic Form with validation</h3><p>Let’s say that we need a flexible form that will be able to render different form fields depending on the given number of fields that are specified. This is a typical requirement for forms that need to cater to different geographical locations. For example, in one country you will need to collect a tax number and in another country this is not required.</p><p>Sure, you could just create different templates for each country, but this can become quite repetitive and you will find that there is a lot of copying and pasting and duplicate functionality and this goes against the principles of<br>DRY.</p><p>Creating a template is perfectly fine when you have, say half dozen different locale that you are targeting, but when you are targeting large geographical regions then using a dynamic form is the best option.</p><p>Here is the link to the completed DynamicForm github repo that we will be building: <a href="https://github.com/cagarweyne/DynamicForm">DynamicForm</a></p><p>Formik has quite a few options out of the box that cater to different requirements, we will use Formik to create our own custom dynamic form. I’ve used the create-react-app tool to get a started, we’ll obviously need formik and we’re also going to install <a href="https://github.com/jquense/yup">yup</a>, which we’ll use for validating the inputs:</p><pre>yarn add formik yup</pre><p>This will add the dependencies that we’ll need. We’re going to first clear out some of the create react app boilerplate code and then create a DynamicForm component. Inside this component we will create a simple input using Formik to get started:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ea94ed9f74ec0f2895009318804e0b0/href">https://medium.com/media/9ea94ed9f74ec0f2895009318804e0b0/href</a></iframe><p>This is what is rendered to the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*JHvXXRBHSoI_udtR.png" /><figcaption>Single input form</figcaption></figure><p>We have a single input field with a submit button, there is a bunch of css styles inside the App.css file to give the form some simple styling.</p><p>Let’s go through the code inside DynamicForm component quickly to understand exactly what is happening. First of we’re using the Formik component from Formik and we are using its render function to create a single input. We have passed the onSubmit prop a function that will get called with the form values once they all pass validation.</p><p>This function simply logs out the values to console — you would typically pass a function that will post this data to a server somewhere. Notice we are using the validationSchema prop here as well, this is optional and has been built into Formik.</p><p>We could have used our own validation function, but the Yup schema that it returns is very useful, as all we need to do is define our values and their types. You can read more about Yup schema here on their github <a href="https://github.com/jquense/yup">page</a></p><p>We also have the initialValues prop, here we have to initialize the initial values of the form, even if the form is empty otherwise React will throw an error. The initialValues prop must be an object whose key will be used as the name and the value will be the initial value of the input. In our single input example we have passed in:</p><pre>{ firstName: &#39;Abdi&#39; }</pre><p>This was derived with our function getInitialValues which plucks off the name value and uses that as a key and then assigns the value from the object that is passed in as part of an array of objects in the fields prop. We also have another helper method renderFeilds this method simply maps over the given fields and returns a Field component.</p><p>There are a few ways that we can render with the Field component and here we are passing markup that we want rendered by using the Fields render prop. The render prop simply returns some jsx that we pass to it.</p><p>Here we also get access to this particular field’s value, name, onChange, and OnBlur functions via the field key. As you can see we are destructuring that from the props parameter and passing these to the input that we return from the Field component. So this:</p><pre>&lt;input <br>{...field} <br>type=&#39;text&#39; <br>/&gt;</pre><p>Is Equivalent to:</p><pre>&lt;input <br>name={field.name} <br>value={field.value} <br>onChange={field.Onchange} <br>onBlur={field.onBlur} <br>type=&#39;text&#39; <br>/&gt;</pre><p>The first way just condenses our code and makes it more terse. Inside the renderFields method we are also using the label prop from the fields object that we passed in.</p><p>The last part of the jigsaw is the validation file, we are making use of the built in support for Yup schema in Formik and we are passing in our own yup schema that will be used to validate each field value.</p><p>Inside the validation file we create a new Yup schema and define each fields type using the many different functions that are made available by Yup to validate each field.</p><p>It is important to understand here that the name of each schema must match<br>the name of each value that we initialize in the Formik component.</p><p>This means that the names that we use in initialValues must match the names that we declare inside the validation file. So, in our case here we have a single initial value called firstName and inside our validation file we also have a firstName key of the Yup schema.</p><p>This is very important, otherwise Formik will not know which validation rule to apply against which input value.</p><p>Inside our validation file we are simply going to validate the input to this field by running matches() function that will return either true or false based on the criteria that we wish to match:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ee3bba7a1a607293f177d319ec43d6/href">https://medium.com/media/43ee3bba7a1a607293f177d319ec43d6/href</a></iframe><p>In our example here we are checking to make sure that the entered values are alphabet characters only for the first name, and we are using the required method to make this a required field that cannot be empty.</p><p>We are also specifying a maximum of 35 characters as input. So, let’s switch our focus back to the Formik component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/440438f5c12cc0f4eb90d670eb76d3ed/href">https://medium.com/media/440438f5c12cc0f4eb90d670eb76d3ed/href</a></iframe><p>The line &lt;form onSubmit={form.handleSubmit}&gt; calls our onSubmit function that we supplied as a prop to onSubmit, our function only gets called after validation has been run and all of the field values have passed this validation.</p><p>Formik will not call the onSubmit function unless this validation is successful. Finally we have a button with a type submit that we can use to submit our form data.</p><p>So far this is really simple stuff, however we have created a powerful foundation that will enable us to reuse this form in so many ways. We are currently dynamically rendering each field component as it is passed in, and we are applying validation on the fly as the values change.</p><p>This is the default behavior and we can change this using the validateOnChange prop and set that to false if we do not want to validate on changes.</p><p>We can add as many input fields as we need, let’s add a few more fields to our component by simply adding more field objects to the fields array that we pass to DynamicForm as a prop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96caff10b1ae62b105c989ae4b4e8c3/href">https://medium.com/media/f96caff10b1ae62b105c989ae4b4e8c3/href</a></iframe><p>We have expanded the number of fields that we want to render and if you save and view the browser you will now see that we have an additional four fields that have been rendered.</p><p>This is pretty cool, because it means that we don’t have to write the markup for each additional field and likewise if we want to remove a field all we have to do is remove the object that corresponds to that field.</p><p>It’s also worth noting that since we are using Yup validation, we need to also add a validation rule for each new additional field that we add to our form inside our validation file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1fc3a733a15bcb15ef1b3c843f88af5/href">https://medium.com/media/f1fc3a733a15bcb15ef1b3c843f88af5/href</a></iframe><p>We now have validation for each field that we are rendering with DynamicForm, now if we want to remove a particular field from our form we need to now make sure that we remove not only that particular fields object in the fields array, but also the corresponding validation key inside the validation file.</p><p>If we don’t delete this field from the validation file and we only delete it from the fields object and that field is required, Formik will not submit the form since there isn’t a value for that deleted field being passed to the validation file. This is why we need to make sure that the validation file keys not only match by the names of the values but also make sure that the values are the same in Formik and the Yup schema.</p><p>We can also change the ordering of the fields as we wish as well, so, say we wanted to have city come before the address field we can easily do this by simply changing the ordering inside our fields array that we pass as a prop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53f67e90cd4474597f52451988c2f6dc/href">https://medium.com/media/53f67e90cd4474597f52451988c2f6dc/href</a></iframe><p>Now if we save this change and view the browser, you will now see that the city field comes before the address input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*zzGr_pwB_w-pO5PB.png" /></figure><p>We now have a flexible form that we can add, remove and order as we need, however, our form currently only has input fields of text and say we wanted to add a drop down option, or we wanted the user to be able to send a message in a text area or maybe we need to also have a checkbox? We can further extend our dynamic form by adding these different types of input.</p><h3>Add more input types to our dynamic form</h3><p>In our renderFields method we can do a check on the type key of each form field that is passed in as a prop. Currently, all of our form fields are just text inputs.</p><p>Let’s add a check to see if the type is select and if this is the case then we want to render a dropdown element. We will delegate this to another class method and let’s call this renderSelect:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e74f1e24cd32ae447407fe9fca8ec128/href">https://medium.com/media/e74f1e24cd32ae447407fe9fca8ec128/href</a></iframe><p>The renderSelect method will take the input object and return a select element. For this we have made use of the Field component&#39;s render prop and like before we get access to the field object via the props that are passed as a parameter to the render prop function.</p><p>In the render prop function we create a default option with a value of ‘Please Select’ and we use this as a default option. Notice we are expecting a data key to be available on the input object that is passed to renderSelect, this data key will be an array that contains each option that we want to render.</p><p>We map over this data array to return an array of jsx &lt;option&gt; elements. We then concatenate the default option with the rest of the options into another array and use that as the select options.</p><p>We need to now add a check inside of the renderFields method to check for the existence of a select input field in the fields<br> prop that is passed in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/196fe26c0e2d9664582d5edc1099b84d/href">https://medium.com/media/196fe26c0e2d9664582d5edc1099b84d/href</a></iframe><p>Now all that’s left to do is to actually add the select field’s data into our fields prop as an object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce5bffdff09db118c70eaa600f16176/href">https://medium.com/media/5ce5bffdff09db118c70eaa600f16176/href</a></iframe><p>Notice that we have an extra key for the select input type; data, this is list of the options that we want to use for the drop down list. As for the initial value we are setting this to Please Select so that is selected as the default option.</p><p>Next, we need to add this field to the validation file. We will make this a required field and use a test function to make sure that the default value is not selected. So our updated validation file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80ed93edd687aed581d1119f071025ee/href">https://medium.com/media/80ed93edd687aed581d1119f071025ee/href</a></iframe><p>If we now save our files, we should see our newly added select input with the specified options on the page and we can use the drop down to make a selection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/0*78Ky3bFn3JUrpKHj.png" /></figure><p>You will notice that if we don’t make a selection or we enter invalid data and press the submit button nothing happens on the page. This is because there are errors on form when we run the validation against it. We need to be able to show these errors to the user and highlight the fields that the user needs to correct.</p><h3>Show validation errors</h3><p>Formik provides a host of props, and one of the most useful ones are the errors, touched and isValid. Inside our render prop methods we get access to what&#39;s called the &#39;formikBag&#39;. This is an object of the entire forms values, touched, errors and a whole host of props.</p><p>In order to show the user validation errors, we will use the errors and touched props. We can also use the isaValid prop to enable and disable the submit button but we will suffice with the highlighting the fields that have invalid input.</p><p>The errors and touched props are an object with the name of each field as a key. When there is an error the errors object will contain the name of the field as the key, likewise the touched object will also have the names as keys to show that particular field has been visited by the user.</p><p>We will pull off the errors and touched object from the props parameter that is passed to the render prop and use these to conditionally apply an ID to each form field:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb973f69abcc0966c117c23ee68186d/href">https://medium.com/media/9bb973f69abcc0966c117c23ee68186d/href</a></iframe><p>We check to see the errors and the touched object and if these are both present for each input field then we return the string ‘hasError’ as the ID value. We then add this as an ID value to the input element.</p><p>The errors and touched object values get updated for each onChange event, so this means that whenever the field is touched and there is an error on that field the value for the ID will contain ‘hasError’ and will apply the error validation css to that field. Here is the updated renderSelect method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f35e6da1e7f8605dcdacafe9f3dca7/href">https://medium.com/media/a4f35e6da1e7f8605dcdacafe9f3dca7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*UrJyLSj61lELAn8H.png" /></figure><p>We can also add a small alert banner that will be shown along with highlighted fields with errors. Note you can use the errors object to tell the user exactly which field needs to be corrected, but since we are highlight these we can suffice with a simple message to tell the user that there are errors that need to be corrected.</p><p>So, inside the render method of the DynamicForm component we can add this simple error banner that will show whenever there is at least<br>one error in the form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ae32ea4f40ae62eee5204dbb6f82a3a/href">https://medium.com/media/3ae32ea4f40ae62eee5204dbb6f82a3a/href</a></iframe><p>In the render prop function, we also get access to the formikBag this is all the props that are available to the form including errors and touched object.</p><p>Here we test the presence of at least one error and if that it is the case, we assign the class error to the errorMessageShow variable, otherwise we set the class name to &#39;hidden&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/0*CzEscV5nBQTKW0dM.png" /></figure><p>Remember, the error object is updated on every change, so this means that if the user corrects the errors in the form, the errors object will also be updated and will consequently be empty meaning that there is no error.</p><p>This will result in an ‘hidden’ being assigned as the class value and the error banner will be hidden from view.</p><p>We can further extend the form by adding in more form field types like text and checkboxes. For this we can add two more methods,<br> and you can guess what we’ll call them!renderCheckBox and renderTextArea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3118f92580310c1349b8e7f5227617bd/href">https://medium.com/media/3118f92580310c1349b8e7f5227617bd/href</a></iframe><p>Then inside the renderFields method&#39;s map function we will check the type key accordingly and call each method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/388dc3c29ff216f2659e5eef973b606f/href">https://medium.com/media/388dc3c29ff216f2659e5eef973b606f/href</a></iframe><p>As we did before, we will need to update the fields prop if we want to add a checkbox or a textarea and also add the required validation for each field respectively:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdb1bfeec334ac15673e1fc394fc858f/href">https://medium.com/media/fdb1bfeec334ac15673e1fc394fc858f/href</a></iframe><p>Now we have an updated form with a variety of form field inputs along with validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*PCNez3eTUWW931f6.png" /></figure><h3>Conclusion</h3><p>Formik is a real game changer, and the great thing about it is that you do not have to learn a new or complex API to use it, since it’s written in pure React. The great thing about that also is that as React is constantly improving, so will your React forms and you can take advantage of new React functionality<br>without worrying about breaking anything.</p><p><em>Originally published at </em><a href="http://fullstackstudent.com/dynamic-react-form-with-formik/">http://fullstackstudent.com/dynamic-react-form-with-formik/</a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aad80ad7e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functions in ES6]]></title>
            <link>https://medium.com/@a.cagarweyne/functions-in-es6-31a2cebbd561?source=rss-6266e3b75525------2</link>
            <guid isPermaLink="false">https://medium.com/p/31a2cebbd561</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6-in-depth]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Abdi Cagarweyne]]></dc:creator>
            <pubDate>Fri, 27 Apr 2018 20:21:21 GMT</pubDate>
            <atom:updated>2018-04-27T20:21:21.676Z</atom:updated>
            <content:encoded><![CDATA[<p>Functions are one of the foundations of the JS language, and it is no surprise that functions have been updated in the latest edition of JS. One of the cool features of functions in ES6 is the addition of default parameters.</p><h3>Default Parameters</h3><p>To make functions more robust and not break when they are called without their expected parameters, we would normally add in default values in the body of the function to make sure that our function didn’t break. Let’s take a simple function that will take 3 parameters and do some computation based on the passed in values or the default fall back ones set in the function body:</p><pre>function box(height, color, url) {<br>    var height = height || 50, <br>        color = color || &#39;blue&#39;<br>        url = url || &#39;google.com&#39;;<br>  <br>    console.log(&#39;height is:&#39;, height, &#39;color is:&#39;, color, &#39;url is:&#39;, url);     <br>    }<br>  <br>    box(75, &#39;green&#39;, &#39;fullstackstudent.com&#39;)// logs: height is: 75 color is: green url is: fullstackstudent.com<br>  <br>    box(); //logs the default values: height is: 50 color is: blue url is: google.com</pre><p>The above function works fine most circumstances but requires some brain power in order to understand what is happening at the top of the function with the default assignments. Also, your function could run into problems when a value that is deemed falsy is passed in as the parameter to the function, for example if we pass in 0 as the height:</p><pre>box(0, &#39;yellow&#39;, &#39;wikipedia.org&#39;); // this logs: height is: 50 color is: yellow url is: wikipedia.org</pre><p>When passing in 0 as the height, the value is evalluated to be falsy, so the right side of the || operation is executed and the height value is assigned to be 50 instead of 0, which is what we intended. We can account for this scenario by doing further checks in the code, but this means more work and more code that has to be written. For example:</p><pre>function box(height, color, url) {<br>    var height = (height !==undefined) ? height : 50, <br>        color = color || &#39;blue&#39;<br>        url = url || &#39;google.com&#39;;<br>  <br>    console.log(&#39;height is:&#39;, height, &#39;color is:&#39;, color, &#39;url is:&#39;, url);     <br>    }<br>  <br>    box(0, &#39;yellow&#39;, &#39;wikipedia.org&#39;); //behaves as expected and logs: height is: 0 color is: yellow url is: wikipedia.org</pre><p>You will notice that the above function declaration is terse, in that the default parameters are actually assigned when setting the parameters themselves and you will also notice that when we pass in `0` as the first argument it isn’t taken as falsy value and the default parameter for height is not used. The default assignment for the height in ES2015 equivalent to the explicit checking of the parameter to see if it is undefined, this is something that you don’t have to do yourself anymore.</p><h3>Expressions as default values</h3><p>In ES6 you can use any valid expression as the default values, including function calls. Let’s create a function call as default value for our height parameter:</p><pre>function setHeight(value) {<br>      return 10 * value; <br>    }<br>    <br>    <br>function box(height = setHeight(10), color = &#39;blue&#39;, url = &#39;google.com&#39;) {<br>  <br> console.log(&#39;height is:&#39;, height, &#39;color is:&#39;, color, &#39;url is:&#39;, url);     <br>    }<br>    <br>box();//logs: height is: 100 color is: blue url is: google.com</pre><p>This is very interesting, because it means that you can invoke other functions that return values when you declare the function that will use that return value. This makes for a powerful default parameter structure in ES2015. Also, you can use a previous parameter as the default paramter for any subsequent parameters:</p><pre>function multiply(num1, num2 = num1) {<br>      return num1 * num2; <br>    }<br>    <br>console.lo(multiply(2));//returns 4</pre><p>The above multiply function takes two arguments and sets the second parameters default value to be the first. Note that this will only work for parameters that come after the first one. For example, you can’t make the default value for the first parameter to be the second parameter:</p><pre>function multiply(num1 = num2, num2) {<br>    return num1 * num2;<br>    }<br>    <br>console.log(multiply(3, 3));     // 9<br>console.log(multiply(1));        // throws error</pre><h3>Rest</h3><p>So far we have seen some really cool additions to the language in ES2015 and the spread and rest operators are another great feature added to JS. Let’s start with the rest operator first, to understand why it’s useful we need to look at the arguments object that is available inside all functions.</p><p>You can examine all of the parameters passed to function in the arguments object, this is an object that behaves very much like an array, but is actually an object. Let’s take a look at an example of using the atguments object in a function in ES5:</p><pre>function sum() {<br>    //convert arguments object into an array using the the array slice method<br>     var numbers = Array.prototype.slice.call(arguments);<br>     var result = 0;<br>  <br>     //loop over the numebrs array and add each index value to result on each iteration<br>     numbers.forEach(function (number) {<br>         result += number;<br>     });<br>     return result;<br>    }<br>    console.log(sum(1));             // 1<br>    console.log(sum(1, 2, 3, 4, 5)); // 15</pre><p>In the sum function above it’s not at all obvious that the function can handle more than one parameter. You could define several more parameters, but you would still not know that this function can take any number of parameters and is a variadic function.</p><p>If there are complex multiple parameters such as objects and arrays, you have to keep track of where to start your index when looping over the arguments object. As you can see this is a little cumbersome and the function can break if we pass it multiple parameters that aren’t the correct type.</p><p>ES2015 introduced a new operator called rest parameters to help us access the parameters passed to a function. Let’s look at it in action to get a better understading:</p><pre>function sum(…numbers) {<br>    let result = 0;<br>    numbers.forEach(function (number) {<br>      result += number;<br>    });<br>    return result;<br>    }<br>    console.log(sum(1)); // 1<br>    console.log(sum(1, 2, 3, 4, 5)); // 15</pre><p>The 3 dots before the parameter indicate that all of the arguments that are passed into the function when it’s call should be gathered in ann array called numbers. This is a real array and you can use all of the normal array methods on it, in this case we are using the forEach array method to access each index value and add it to the result variable.</p><p>This is a much easier and cleaner to access parameters in a function, and from the function declaration we can see that this function accepts any number of arguments and that these arguments will be gathered into an array called numbers.</p><p>There is a key restriction when using rest parameters in your functions, and that it no other named arguments can follow in the function declaration. This means that you can’t have something like this:</p><pre>function sum(…numbers, last) { // causes a syntax error<br>    var result = 0;<br>    numbers.forEach(function (number) {<br>      result += number;<br>    });<br>    return result;<br>    }</pre><h3>Spread</h3><p>The spread operator uses the exact same syntax, and you could think of it as acting completely oppositely to the rest operator. Whereas the rest operator gathers all of the parameters passed in to the function into an array, the spread operator spreads out the contents of an array into individual values. The spread operator uses the same 3 dots to achieve this:</p><pre>let numbers = [1, 2, 3]; <br><br>function sum(num1, num2, num3) {<br> return num1 + num2 + num3; <br>}<br>    <br>sum(...numbers);</pre><p>The spread operator uses exactly the same syntax as the rest operator, however, it behaves differently depending on where it is used. Here we are calling the sum function and passing it our arguments using the spread operator.</p><p>The operator spreads out each of the contents into individual parts and then the function merely adds up these individual values. You could think of it as acting like the apply method on arrays. So, if we used apply instead we would get the same effect:</p><pre>let numbers = [1, 2, 3]; <br><br>function sum(num1, num2, num3) {<br> return num1 + num2 + num3; <br>}<br>    <br>sum.apply(null, numbers);</pre><p>You can also use the spread operator in place of the concat method:</p><pre>let a = [2,3,4];<br>let b = [ 1, ...a, 5 ];<br>    <br>console.log( b ); // [1,2,3,4,5];</pre><h3>Arrow functions</h3><p>Another fantastic addition to the language are arrow functions. If you are familiar with CoffeeScript the this is a great addition for you. Not only do fat arrows make your code more terse, but they also help address one of the most confusing parts of JS, the this context. Arrow functions are incredibly easy to create and at first glance you would have to look carefully to understand that it is in fact a function:</p><pre>var foo = (a, b) =&gt; a * b;</pre><p>Yes, the above is a function, and you can even make it more terse, by removing the parenthesis if you only have one parameter:</p><pre>var bar = a =&gt; a * 5;</pre><p>The above are examples of valid function ES6, the arrow definition for function consists of the parameters if there are any and then followed by the curly braces . The curly braces are required when there is more than one expression.</p><h3>Arrow functions are always expressions</h3><p>A seasoned JS developer will know the difference between a function declaration and a function expression. Just to recap, a function declaration is a named function variable that isn’t assigned to a variable:</p><pre>function foo() {<br> console.log(&#39;foo&#39;); <br>}</pre><p>A function expression uses a variable assignment:</p><pre>var foo = function() {<br> console.log(&#39;foo&#39;);<br>}</pre><p>It is worth keeping in mind that arrow functions will always be function expressions and are also anonymous function expressions.</p><h3>Binding of this with arrow functions</h3><p>If you have done any noteworthy coding with JS, then you will have come across the issue with the this keyword. This was a particular point of confusion when it comes to programming wit the this keyword and has generated a lot of complaints from the developer community.</p><p>As a result, the ES6 implementation addressed this issue with the introduction of the arrow functions. To understand what the problem with the this keyword was in ES5, let’s have a look at an example:</p><pre>var person = {<br>    firstname: &quot;Abdi&quot;, <br>    lastname: &quot;Cagarweyne&quot;,<br>    getFullName: function() {<br>        console.log(this.firstname, this.lastname);<br>        }<br>    }<br>    <br>    person.getFullName();// Abdi Cagarweyne</pre><p>The above object gas has two properties and a method, which simply logs to the console the `firstname` and `lastname` properties. This is all well and good and the `this` context works just fine. However, you will run into problems when you change contexts or closures come into the equation, for example:</p><pre>var person = {<br>    firstname: &quot;Abdi&quot;, <br>    lastname: &quot;Cagarweyene&quot;,<br>      getFullName: function() {<br>         var name = function() {<br>         console.log(this.firstname, this.lastname);<br>         }<br>  <br>         return name(); <br>  <br>      }<br>    }<br>    <br>    person.getFullName();//undefined undefined</pre><p>When we call the getFullName method, we get undefined undefined, this is the not the behavior that we expected and this is one of the quirks of JS. To fix this we have two options, we can use the `var self = this hack`:</p><pre>var person = {<br>    firstname: &quot;Abdi&quot;, <br>    lastname: &quot;Cagarweyene&quot;,<br>      getFullName: function() {<br>         var self = this; <br>         var name = function() {<br>         console.log(self.firstname, self.lastname);<br>         }<br>  <br>         return name(); <br>  <br>      }<br>    }<br>    <br>    person.getFullName();//Abdi Cagarweyne</pre><p>When we reference the context of this by assigning it to a variable inside the outer function, we will have access to inside the inner functions via a closure. So, in order to keep the context we simply use the self instead of the function’s this keyword, which points to the global window object in the example above. We can also fix the problem with this using the bind method that is available on functions:</p><pre>var person = {<br>    firstname: &quot;Abdi&quot;, <br>    lastname: &quot;Cagarweyene&quot;,<br>      getFullName: function() {<br>         var name = function() {<br>         console.log(self.firstname, self.lastname);<br>         }.bind(this)<br>  <br>         return name(); <br>  <br>      }<br>    }<br>    <br>    person.getFullName();//Abdi Cagarweyne</pre><p>ES2015 enables us to eliminate much of the frustrations with the this keyword in JS by using fat arrow functions. So, we can rewrite the above examples using arrow functions and also address the issue of the value of <em>this</em>:</p><pre>var person = {<br>    firstname: &quot;Abdi&quot;, <br>    lastname: &quot;Cagarweyene&quot;,<br>    getFullName: function() {<br>      var name = () =&gt; {<br>        console.log(this.firstname, this.lastname);<br>      }<br>  <br>      return name(); <br>  <br>    }<br>  }<br>    <br>    person.getFullName();//Abdi Cagarweyne</pre><p>By using the arrow function instead of a normal syntax with the function keyword, we get the behavior that is desired. This is because the `this` keyword binding in arrow functions is lexical. This means that arrow functions do not have a stand-alone this value binding, rather the value is decided by the closest containing non-arrow function and in our example that is the `getFullName` function. So, essentially the fat arrow `=&gt;` replaces the `var self = this` or `bind(this)`.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31a2cebbd561" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>