reactjsmodalpopup

Close popup on form submit and display success/error message on parent component in reactjs


I am opening a form to add a user in a popup using the toggle method. I want to close the toggle on success and display a message in my parent component.

This is my toggle method
`````````````````````````````  
 toggle = () => {
  this.setState({
  modal: !this.state.modal
 });
 }

  <Modals title={'Add User'} isOpen={this.state.modal} toggle= 
   {this.toggle} />

   This is the method written in modal popup
   addApi = (data) => {
    axios.post(`http://***************/api/adduser`,data) //api call
    .then(res => {
    this.setState({
      successMsg : 'Record Added Successfully'
    })
    this.props.toggle(); // to close pop up. Is it right?
  })

   In my parent component:
  let {successMsg}=this.state;
     {successMsg ? successMsg : ''}

 ````````````````````````````````````````````````````

How do I close the pop-up the correct way and display a success message in the parent component?


Solution

  • Yeah, actually what you want is success message to be passed to your parent component with modal closed.You can do something like this

    addApi = (data) => {
            axios.post(`http://***************/api/adduser`,data) //api call
            .then(res => {
            this.setState({
              successMsg : 'Record Added Successfully'
            })
            this.props.toggle({
              successMsg : 'Record Added Successfully'
            }); // to close pop up. Is it right?
        //now your parent component will get successMsg in an object, you can use it whereever you want
    
          })
    

    In your parent component , you can add something like this:

    toggle = (data) => {
      this.setState({
      modal: !this.state.modal,
      successMsg: data.successMsg
     });
     }
    

    Is it what you wanted ?