javascript - tab containers in ReactJS: only render selected child vs. using `display:none` -
i built simplistic tab container in reactjs using idea container component keeps in state integer index denoting tab pane display , renders child (from this.props.children
array) found @ index position.
the gist of approach was:
const tabcontainer = react.createclass({ props: { tabnames: react.proptypes.arrayof(react.proptypes.string).isrequired }, getinitialstate: function() { return { activeindex: 0 }; }, settab: function(n) { this.setstate({activeindex: n}); }, render: function render() { const childtorender = this.props.children[this.state.activeindex]; return ( <div classname='tab-container'> <tabs tabnames= {this.props.tabnames} active = {this.state.active} settab = {this.settab} /> <div classname='tab-pane'> {childtorender} </div> </div> ); } });
i.e. indexed child selected , rendered (i've omitted sake of simplicity code handling edge case this.props.children
not array
).
i found out approach unsatisfactory when user selected different tabs, component corresponding pane render mounted , unmounted repeatedly , state panes had not preserved.
ultimately, used approach in children rendered , panes, except selected one, assigned class hidden
used style panes as: display:none
. when later solution used panes remained mounted after user clicked through various tabs , state had wasn't lost user cycled through tabs.
my questions are:
- was initial approach (where specific child rendered) anti-pattern or there other mechanism have used preserve state of individual panes or prevent them being unmounted?
- if initial approach indeed anti-pattern how can anti-pattern expressed more generally?
i don't think initial approach antipattern @ all. choosing whether or not mount/unmount in logic dependent on circumstances. if want state preserved, don't unmount. if want fresh element, complete call getinitialstate
, unmounting right way go.
as easy counterexample, consider react-router. router unmounts/remounts components on route change. , route changing higher order of tabbing.
but given situation want state preserved, think solution proper one. might want take @ material-ui, similar in tabbing: https://github.com/callemall/material-ui/blob/master/src/tabs/tabtemplate.js