Skip to content Skip to sidebar Skip to footer

How To Send Data From Dialog Back To Parent Container With React?

I have a react-big-calendar (The parent container), I have also a select which, the events of the calendar are fetched according to this select ( doctor name ) and I have a button

Solution 1:

I think, you can achieve it using code like this:

exportdefaultComponentA extendsComponent {
  // set localStorage to bar state value// via click or whatever ...
    foo () {
    this.setState({
      bar: localStorage.getItem('bar')
    })
  }

  render () {
    // send the value of state to ComponentBreturn<ComponentBfoo={this.state.bar}>
  }
}

Into your component

exportdefaultclassComponentBextendsComponent {
    render () {
    // display the value of foo propreturn<div>{this.props.foo}</div>
  }
}

Note: You can always try to get the content of your localStoragedirectly from the ComponentB(Maybe using ComponentDidUpdate???) but the way I show you is better.

Solution 2:

Don't save events in your state, in Popup access the events directly from props.

In your Calendar, create a function that'll update the state.

updateEvents = (events, callback = () => {}) => {
  this.setState(
    {
      events
    },
    callback
  );
};

<PopupupdateEvents={this.updateEvents}ref={this.ModalAjoutb}id_user={this.state.id_user}events={this.state.events} />

Popup

exportdefaultclassPopupextendsComponent {
  constructor(props) {
    super(props);
  }

  handleAjouterb = id_user => {
    this.setState(
      {
        openPopupAjout: true,
        id_user
      },
      () => {
        this.fetchingPopup(
          this.state.id_user,
          this.state.identifiant_user,
          this.state.nom_user
        );
      }
    );
  };
  fetchingPopup = (id_user, identifiant_user, nom_user) => {
    const praticiensCached = JSON.parse(
      localStorage.getItem('Liste de praticiens ')
    );
    for (let j = 0; j < praticiensCached.length; j++) {
      if (id_user === praticiensCached[j].id_user) {
        identifiant_user = praticiensCached[j].identifiant_user;
        this.setState({ nom_user: praticiensCached[j].nom_user });
      }
    }
    handleValider = event => {
      event.preventDefault();
      const praticiensCached = JSON.parse(
        localStorage.getItem('Liste de praticiens ')
      );
      for (let j = 0; j < praticiensCached.length; j++) {
        if (this.state.id_user === praticiensCached[j].id_user)
          this.state.identifiant_user = praticiensCached[j].identifiant_user;
      }

      const formData = newFormData();

      formData.append('identifiant_user', this.state.identifiant_user);
      formData.append('heuredebut', this.state.tranchesC[0].startC);
      formData.append('heurefin', this.state.tranchesC[0].endC);
      formData.append('libelleconge', this.state.libelle);
      axios({
        method: 'post',
        url: process.env.REACT_APP_API_BACKEND + 'add_event_docteur',
        data: formData,
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json'
        }
      }).then(() => {
        fetch(
          process.env.REACT_APP_API_BACKEND +
            'get_liste_planning/start=' +
            moment()
              .startOf('isoweek')
              .subtract(14, 'days')
              .toJSON() +
            '&end=' +
            moment()
              .endOf('isoweek')
              .add(2, 'months')
              .toJSON() +
            '&identifiant_user=' +
            this.state.identifiant_user
        )
          .then(Response =>Response.json())
          .then(data => {
            let evts = data.ListeResult;
            for (let i = 0; i < evts.length; i++) {
              evts[i].start = moment(evts[i].start).toDate();
              evts[i].end = moment(evts[i].end).toDate();
            }
            this.props.updateEvents(evts, () => {
              localStorage.setItem(
                'Liste récente de planning de ' + this.state.nom_user,
                JSON.stringify(evts)
              );
              localStorage.removeItem(
                'Liste de planning de ' + this.state.nom_user
              );
              localStorage.setItem(
                'Liste de planning de ' + this.state.nom_user,
                JSON.stringify(evts)
              );
            });
          });
      });
    };
  };

  render() {
    return (
      <div><Dialogicon="application"onClose={this.handleClose}title="Organisation des plannings du docteur"
          {...this.state}
          isOpen={this.state.openPopupAjout}
        ><Inputid="libelle"style={{width: '480px' }}
            value={this.state.libelle}onChange={this.handleInputChange('libelle')}
          /><labelclassName="pt-label .modifier"><strong>Date</strong></label><LocaleProviderlocale={fr_FR}><RangePickerid="date"name="date"locale="fr"placeholder={['Datededébut', 'Datedefin']}
              separator="-"onChange={this.handleDateCChange}value={this.state.dateIC}format="DD/MM/YYYY"allowClear={false}
            /></LocaleProvider><labelclassName="pt-label .modifier">
            {' '}
            <strong>Heure de début</strong></label><Timevalue={el.startC}onChange={time => this.handleKeyboardStartCChange(i, time)}
            style={heure}
            disableUnderline={true}
            inputComponent={TextMaskCustom}
            endAdornment={
              <InputAdornmentposition="end"style={{opacity: '0.4' }}>
                {' '}
                <IconButtononClick={() => this.openDialogC(i, el.startC, 'startC')}
                >
                  <istyle={{fontSize: '18px' }} className="zmdi zmdi-alarm" /></IconButton>{' '}
              </InputAdornment>
            }
          />
          <labelclassName="pt-label .modifier">
            {' '}
            <strong>Heure de fin</strong></label><Timevalue={el.endC}onChange={time => this.handleKeyboardEndCChange(i, time)}
            style={heure}
            disableUnderline={true}
            inputComponent={TextMaskCustom}
            endAdornment={
              <InputAdornmentposition="end"style={{opacity: '0.4' }}>
                {' '}
                <IconButtononClick={() => this.openDialogC(i, el.endC, 'endC')}
                >
                  <istyle={{fontSize: '18px' }} className="zmdi zmdi-alarm" /></IconButton></InputAdornment>
            }
          />
          <ClockmaxWidth="xs"open={this.state.isOpenC}onBackdropClick={this.closeDialogC}
          ><TimePickermode="24h"value={this.createDateFromTextValueC(this.state.datePickerValueC)}onChange={this.handleDialogCChange}
            /><DialogActions>
              {' '}
              <ButtonOkonClick={this.closeDialogC}color="primary">
                {' '}
                Ok{' '}
              </ButtonOk></DialogActions></Clock><AnchorButtonstyle={{display: 'inline-block' }}
            intent={Intent.SUCCESS}onClick={this.handleValider}
          >
            Valider
          </AnchorButton></div>
    );
  }
}

Solution 3:

Why not you use context Feature of React React Context API

context.js

exportconst store = {
  something: 'val',
  setSomeThing : () => {}
};

exportconstCalContext = React.createContext(
  store // default value
);

pop-up.js

import {CalContext} from'./context';

classPopupextendsReact.Component {

   updateValue = () => {
     this.context.setSomeThing('new_value');
   }    

   render() {
    let calContext = this.context;

    return (
      <buttononClick={this.updateValue} >
        {calContext.something}
      </button>
    );
  }
}

Popup.contextType = CalContext;

exportdefaultPopup;

calender.js

import {CalContext} from'./context';
importPopupfrom'./pop-up'classcalenderextendsReact.Component {
   constructor(props) {
      this.state = {
         something : 'value'
      }
   }

  setSomeThing = (newVal) => {
    // actual set something code.this.setState({something : newVal});
  }

render() {
let contextVal = { something : this.state.something, setSomeThing : this.setSomeThing }
// The entire state is passed to the providerreturn (
  <CalContext.Providervalue={contextVal}><Popup /></CalContext.Provider>
   );}
}

Solution 4:

Are you looking for something like this

classComponentBextendsReact.Component{
  render(){
    this.props.setInLocalStorage();
    const value = localStorage.getItem("testA");
    return<div>
  This is componentB{value}
  </div>}
}
classComponentAextendsReact.Component{
 setInLocalStorage = ()=>{
   localStorage.setItem('testA', 'Hello');
}
render(){
  return<ComponentBsetInLocalStorage={this.setInLocalStorage}/>
}
}

Solution 5:

You can either use React Context API or Redux.

But if you don't want those, you can use a prop that is a method in your child component, so the parent can capture the event. It is similar Output mechanic from Angular 2+.

Here is an example:

constChildComponent = (onSelect = () => {}) => {
  return<divonClick={() => onSelect('You selected me')}>Child Component</div>
}

constParentComponent = () => {
  return<ChildComponentonSelect={message => console.log(message)} />// You selected me
}

Post a Comment for "How To Send Data From Dialog Back To Parent Container With React?"