score:1

Accepted answer

Issue

The main issue in your code is that you've a bunch of buttons being rendered inside a form and nearly all of them don't specify a button type. The default for buttons is type="submit", so when any of them are clicked they are submitting the form and the form is taking the default submit action which also happens to reload the page. When the page reloads your app reloads and loses the local component state.

Button type attribute

The default behavior of the button. Possible values are:

  • submit: The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a <form>, or if the attribute is an empty or invalid value.
  • reset: The button resets all the controls to their initial values, like <input type="reset">. (This behavior tends to annoy users.)
  • button: The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element's events, which are triggered when the events occur.

Solution

Explicitly specify the button types.

  • The delete button

     <button
       type="button" // <-- "button" type
       onClick={() => {
         removeItem(item);
       }}
     >
       Remove
     </button>
    
  • The form buttons to submit, reset, and open the modal

     <Button variant="primary" type="submit"> <-- "submit" type
       Submit
     </Button>
    
     <Button
       variant="primary"
       type="reset" // <-- "reset" type
       style={{ margin: '0 20px' }}
     >
       Reset Form
     </Button>
    
     <Button
       variant="primary"
       type="button" // <-- "button" type
       onClick={handleShow}
       style={{ margin: '0 15px' }}
     >
       Add Experience
     </Button>
    

Note: The submit button is still going to submit the form and since you've not any onSubmit callback on the Form component this button, as-is, will cause the page to reload. You will want to add a submit handler and call preventDefault on the onSubmit event object.

const submitHandler = e => {
  e.preventDefault();
  // handle form data or whatever
};

...

<Form onSubmit={submitHandler}>
  ...

score:0

Generally we should not remove any item from array based on it's index. So try to remove items based on unique values:-

  const removeItem = item => {
    itemList(oldList => {
      return oldList.filter((arrEle, i) => arrEle.companyName !== item.companyName);
    });
  };

And pass item in removeItem function like below:-

onClick={() => removeItem(item)}

Add key to tr like below:-

<tr key={`${item.companyName}-${index}`}>

Working demo: https://stackblitz.com/edit/react-cxkbge


Related Query

More Query from same tag