coding style - Encapsulation with React child components -
how should 1 access state (just state, not react state) of child components in react?
i've built small react ui. in it, @ 1 point, have component displaying list of selected options , button allow them edited. clicking button opens modal bunch of checkboxes in, 1 each option. modal it's own react component. top level component showing selected options , button edit them owns state, modal renders props instead. once modal dismissed want state of checkboxes update state of parent object. doing using refs call function on child object 'getselectedoptions' returns json me identifying options selected. when modal selected calls callback function passed in parent asks modal new set of options selected.
here's simplified version of code
optionschooser = react.createclass({ //function passed modal, called when user "ok's" new selection optionsselected: function() { var optsselected = this.refs.modal.getoptionsselected(); //setstate locally , save server... }, render: function() { return ( <uneditableoptions /> <button onclick={this.showmodal}>select options</button> <div> <modal ref="modal" options={this.state.options} optionsselected={this.optionsselected} /> </div> ); } }); modal = react.createclass({ getoptionsselected: function() { return $(react.finddomnode(this.refs.optionsselector)) .find('input[type="checkbox"]:checked').map(function(i, input){ return { normalisedname: input.value }; } ); }, render: function() { return ( //modal list of checkboxes, dismissing calls optionsselected function passed in ); } });
this keeps implementation details of ui of modal hidden parent, seems me coding practice. have been advised using refs in manner may incorrect , should passing state around somehow else, or indeed having parent component access checkboxes itself. i'm still relatively new react wondering if there better approach in situation?
yeah, don't want use refs really. instead, 1 way pass callback modal:
optionschooser = react.createclass({ onoptionselect: function(data) { }, render: function() { return <modal onclose={this.onoptionselect} /> } }); modal = react.createclass({ onclose: function() { var selectedoptions = this.state.selectedoptions; this.props.onclose(selectedoptions); }, render: function() { return (); } });
i.e., child calls function passed in via props. way you're getting selected options looks over-fussy. instead have function runs when checkboxes ticked , store selections in modal state.
another solution problem use flux pattern, child component fires off action data , relays store, top-level component listen to. it's bit out of scope of question though.
Comments
Post a Comment