reactjstypescriptiscroll

How do I call the iScroll refresh methode in a parent react component?


I am struggling currenlty with iScroll in combination with reactJS.
This code samples are written in typescript.

I created a wrapper class for iScroll:

import * as React from 'react';
import * as ReactDOM from 'react-dom';

var iScroll = require('iscroll');        
...

    componentDidMount() {
            this._initializeIScrollInstance();
            console.log(this);
        }

    _initializeIScrollInstance() {
            setTimeout(() => {
                let element = ReactDOM.findDOMNode(this);
                const iScrollInstance = new iScroll(element, this.props.options);
                this._iScrollInstance = iScrollInstance;
            }, 100);
        }

    render() {
                return (
                    <div style={ this.props.style } >
                        { this.props.children }
                    </div>
                )
            }
        }

Then I use it like this in my sidebar class for instance.

<ScrollWrapper>
 <SidebarMenu toggle={ this.toggle.bind(this) } />
</ScrollWrapper>

The problem I am facing is when I toggle a menu inside my sidebar. This means the height changes so I need to call the refresh methode for iScroll.
But how can I achieve this?
Can I get the _iScrollInstance in my parent component?

Its possible to keep a state inside my sidebar and pass it down to the ScrollWrapper as a property and watch for it in componentReceiveProps. But this sounds like a cheap solution to me.
Anyone maybe have a better solution for that kind of problem?


Solution

  • Based on your code :

    <ScrollWrapper>
     <SidebarMenu toggle={ this.toggle.bind(this) } />
    </ScrollWrapper>
    

    I see the child component action (toggle) needs to do something with the parent component (scroll). The idiomatic way to do this is for the parent to give the child component a function (callback) that the child calls when it wants something in the parent to change.

    Note: The recommeded way is to use flux ... but thats a whole other topic (lookup redux which is what I use).