Is there any solution in antd react to check unsaved changes in a component?

Viewed 357

I have a general component named MyModal and it is used in almost 20+ components inside my web-app, I use ant-d modal. Now I have to check that, is there any unsaved changes inside the child component from MyModal: if so, then prompt the user. I can check one by one from each and every child component, by using a new state, but I don't want to do this, infect I want it to be precise and controllable from one component i.e. MyModal component.

How can I check the state changes in the child component (rendered in MyModal)


MY CODE STRUCTURE

MyModal.js

import React, { Component } from 'react'
import { Modal } from 'antd'
    
class MyModal extends Component {
  render() {
    return (
      <Modal {...this.props}>
        {this.props.children}
      </Modal>
    )
  }
}

export default  MyModal

ChildComponent.js

import React, { Component } from 'react'
import { Input, Button } from 'antd'
import MyModal from '../components/MyModal'
    
class ChildComponent extends Component {
  this.state = {
    value: '',
    visible: false,
  };

  onChangeValue = e => this.setState({ value: e.target.value });
  toggleModal = () => this.setState({ visible: !this.state.visible });
  handleOk = () => alert('hello world!')

  render() {
    const { visible, value } = this.state
    return (
      <div>
        <Button onClick={this.toggleModal}>
          Open Modal
        </Button>
        <MyModal visible={visible} onClose={this.toggleModal} footer={[
            <Button key="back" onClick={this.toggleModal}>
              Return
            </Button>,
            <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
              Submit
            </Button>,
          ]}
        >
        <Input value={value} onChange={this.onChangeValue} />
        {/* this is an example component to show you my problem, there are 
            a lot of more fields and states too. */}
      </MyModal>
    )
  }
}

export default  ChildComponent
1 Answers

I have used the Form.Provider from antd and wrapped all the child components in the Form.Provider like below.

  const changedFormsObj = {
    accommodationForm: false,
    userProfileForm: false,
  }



<Form.Provider
  onFormChange={(name) => {
    changedFormsObj[name] = true;
  }}
  onFormFinish={(name) => {
    changedFormsObj[name] = false;
  }}
>
  {children}
</Form.Provider>

When there is a change in any child form component onFormChange method will be triggered with the name of the form in the Form.Provider with that we can set a flag for all the forms and when there is form submit onFormFinish method will be triggered with the name of the form. With this two we can decide whether the form changes are saved or not for all the forms in the parent component itself.

For the more info check the below link.

https://ant.design/components/form/#Form.Provider

Related