Mr_Thorynque Mr_Thorynque - 2 months ago 45
React JSX Question

Adding tab dynamically upgradeElement

When I add a tab with react, its parent element is already upgraded. So calling upgradElement has no effect and the added tab doesn't work.
What solution, recreate all tabs with the container and upgrade it ? React just update DOM component in this case I need to dismount component ?

Answer

How about calling componentHandler.upgradeElement() or componentHandler.upgradeDom() in the componentDidUpdate phase of the specific component

    componentDidUpdate() {
        componentHandler.upgradeElement(this.refs.myElement);
        //or componentHandler.upgradeDom('MaterialTabs');
    }

EDIT 1 Tab Component

    componentDidUpdate() {

        componentHandler.upgradeDom();
    }

    newTab() {
        this.setState({
            newtab: 1
        });
    }

    render() {

        return (<div className="mdl-layout mdl-js-layout mdl-layout--fixed-header" key={this.state.newtab}>
            <button onClick={this.newTab.bind(this)}>Add Tab</button>
                <header className="mdl-layout__header">
                    <div className="mdl-layout__tab-bar mdl-js-ripple-effect">
                        <Link to="/tabtest" hash="#scroll-tab-1" className="mdl-layout__tab is-active">Tab 1</Link>
                        <Link to="/tabtest" hash="#scroll-tab-2" className="mdl-layout__tab">Tab 2</Link>
                        { this.state.newtab ?
                        <Link to="/tabtest" hash="#scroll-tab-3" className="mdl-layout__tab">Tab 3</Link> : null}
                    </div>
                </header>
            <div className="mdl-layout__content">
                <section className="mdl-layout__tab-panel is-active" id="scroll-tab-1">
                    <div className="page-content">Tab 1</div>
                </section>
                <section className="mdl-layout__tab-panel" id="scroll-tab-2">
                    <div className="page-content">Tab 2</div>
                </section>
                { this.state.newtab ? <section className="mdl-layout__tab-panel" id="scroll-tab-3">
                    <div className="page-content">Tab 2</div>
                </section> : null}
            </div>
        </div>);

    }

I did some tests and could reproduce the problem. What helped was to put the key attribute on the root element of the tab component. When adding a new tab this key must change and react will throw away the component and rerender completly. This way all material-design-lite properties get lost and after calling upgradeDom or upgradeElement it works.

React and Material-Design-Lite

Material-Design-Lite source

Comments