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

WSO2 ESB Worker Manager Cluster without a Load Balancer

XML to XML transformation via Smooks Mediator in WSO2 ESB

JMS 2.0 Support in WSO2 ESB