Ad

How To Pass Variable Outside Method's Scope In React?

- 1 answer

I have got a variable abc inside render method and would like to pass variable to navigateNext method. I know we can declare a global variable outside. However, I would like to know if there's a react's way to do it.

var SelectedTopicPage = React.createClass({
    getInitialState: function() {
      return{
        topicPageNo: 0,
        total_selected_topic_pages: 1
      }
    },
    navigateBack: function() {
        let topicPageNo;
        if (this.state.topicPageNo > 0){
            topicPageNo = this.state.topicPageNo - 1;   
        }
        else {
            topicPageNo = 0;
        }
        this.setState({topicPageNo : topicPageNo});
    },
    navigateNext: function() {
        let topicPageNo = this.state.topicPageNo + 1;
        this.setState({topicPageNo : topicPageNo});
        console.log(abc);
    },
    render: function() {
        let topicsID = this.props.topicsID;
        let navigateNext = this.navigateNext;
        let navigateBack = this.navigateBack;
        let topicPageNo = this.state.topicPageNo;
        return (
            <div>
                {this.props.topicPages.filter(function(topicPage) {
                    return topicPage.topic_no === topicsID; // if condition is true, item is not filtered out
                }).map(function (topicPage) {
                    let abc = topicPage.topic_pages.length;
                    return (
                        <div>
                            <div>
                            <SelectedTopicPageMarkup headline={topicPage.topic_pages[0].headline} key={topicPage.topic_no}>
                                {topicPage.topic_pages[topicPageNo].description}
                            </SelectedTopicPageMarkup> 
                            </div>
                            <div>
                                <NextPrevBtn moveNext={navigateNext} moveBack={navigateBack}/>
                            </div>
                        </div>
                    );
                })}
            </div>
        );
    }
});
Ad

Answer

Make abc an input parameter to your navigateNext function. (Aside: Please give it a better name than abc).

navigateNext: function (abc) {
    let topicPageNo = this.state.topicPageNo + 1;
    this.setState({topicPageNo : topicPageNo});
    console.log(abc);
},

Now use it where you define the function callback:

<NextPrevBtn moveNext={this.navigateNext.bind(this, abc)} moveBack={this.navigateBack}/>

You'll also need to use bind on the anonymous function passed to map, to ensure this is in scope. i.e.

}).map(function (topicPage) {
    let abc = topicPage.topic_pages.length;
    return (
        /* etc */
    );
}.bind(this))}
Ad
source: stackoverflow.com
Ad