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):
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:
const [isFieldChanged, setisFieldChanged] = useState(false);
I am using handleClick function this to set useState variable:
const handleClick = () => {
setisFieldChanged(true);
};
These are all the fields and this is how I have set the default value:
const [inputFields, setInputFields] = useState([
{
fieldName: "",
label: "",
fieldSet: "",
cardinality: 0,
required: false,
defaultValue: "",
weight: 0,
},
]);
Below is the code for ternary statement:
<Card
id={`${inputField.id}`}
className={
isFieldChanged &&
index !== 0 &&
(inputFields.length) <= (index + 1) &&
(inputField.cardinality !== 0 ||
inputField.fieldName.length !== 0 ||
inputField.label.length !== 0 ||
inputField.fieldSet.length !== 0 ||
inputField.required !== false ||
inputField.defaultValue.length !== 0)
? " mt-2 border border-warning"
: " mt-2 "
}
>
For each of the form control I am adding onKeyPress to calling the handleClick function:
<Form.Control
type="text"
placeholder="fieldName"
name="fieldName"
data-cy="name-text-field"
value={inputField.fieldName}
onChange={(event) => {
handleInputChange(index, event);
}}
onKeyPress = {(event)=>{
handleClick(index, event);
}
/>