Skip to content
Advertisement

How to find out if the user has enter any value in the input field in react

How to find out if the user has enter any value in the input field in react.

What I am trying to achieve is I would like to show a border around the card when the user enters the text/integer into one of the input fields inside that cards and does not click on the save button.

So border should be added to the card containing at least one of all the unsaved input fields and also changed input fields.

I am using dynamic form mentioned in the link below.

This is the link of how my dynamic form is structured (Sample Code):

Example Dynamic form link

Dynamic form is a form repeater, wherein when I click on the “add a new row” button. the a new card will be added to the react page.

This new card will have a same set of fields with the same default values. when the user changes any of the input field in the card. a border needs to be added to the card. if the user clicks on the save button the input fields should be saved.

When make changes to a individual input fields of a card, that card is indeed get a border, however when I add a new card. the border for the old card with unsaved input fields is removed.

I have been trying to solve this for a week now. I am not using formik or react-hook-form. I am using react-bootstrap library.

I am finding it difficult to change the border of the card as and when the user enters data into the input field.

I am using a ternary statement to check if the fields are changed are not.

I am using a useState hook like this:

JavaScript
JavaScript

These are all the fields and this is how I have set the default value:

JavaScript

Below is the code for ternary statement:

JavaScript

For each of the form control I am adding onKeyPress to calling the handleClick function:

JavaScript

Advertisement

Answer

What you need is two different states – one for saved and one for current data:

JavaScript

Add an onChange event to your Form.Controls:

JavaScript

Define when there is unsafed data: you can compare both states with each other. It’s not sufficient to just say “it’s different when user typed something”, because it can be deleted again, so the states are the same again:

JavaScript

Finally, on save, you have to copy the current data state to the saved data state and call your API to persit the data:

JavaScript

Use “dataUnsafed” to set styles on your card, here I just set a thicker border:

JavaScript

https://codesandbox.io/s/busy-architecture-7it9g9

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement