Conditional Enabling of Submit button in a form using React

Introduction

Well, today I am going to discuss a very common and useful topic about forms in React. At least most of you as front end developers would have encountered with this scenario. The use case we are going to address today is something like this.

Let’s say we have a simple application which enables us to add new users. For the simplicities sake let’s assume this input form consists of first name, last name and age. We make first name and last name mandatory while keeping age as an optional field. So the submit button of the form should get enabled only if the user has entered some values to both the first name and last name fields. In all other situations the submit button should be disabled. Check out the scaffolding below for more details. Notice that the submit button is disabled now since a value is not given for the First Name input field.


Workshop

Well, how are we going to address this requirement elegantly. I am using redux forms to get this thing done. We gonna enable submit button conditionally based on the values of input fields in our form. Let me first share the code with you and then I’ll explain it to you. Check out the code below.


First we need to connect our form to the application level redux state, so that we can get hold of the values later. For that we use connect helper. Then we fetch first name and last name properties from our application level state. These values are finally returned from our wrapped component. The values are then used inside the form to enable submit button conditionally. The isSubmitEnabled function is responsible for that. At last, this boolean flag is used to render the submit button accordingly.  You may find the code for entire solution here.


Conclusion

Well, it was a simple, yet very useful thing. We made it elegantly and smartly with a fairly less amount of code. Our code is much more simple, readable and composable with this solution. I hope that you will be using this somewhere down the line in your projects. That does it for this session. I’ll see you next time.

Comments

Popular posts from this blog

Introducing Java Reactive Extentions in to a SpringBoot Micro Service

Optimal binary search trees

Combining the emissions of multiple Observables together using RxJava Zip operator in a Spring Boot Micro service