Ad

How To Pass A Variable From One Method To Another In React

- 1 answer

I have a component called TopicsList in which there is a variable called topicsID inside onClick method. I would like to pass variable to render method topicsID={topicsID} however its giving undefined error.

var TopicsList = React.createClass({

    getInitialState: function () {
        return {
            isTopicClicked : false,
            topicPages
        };
    },

    onClick: function (topicID) {
        this.setState({isTopicClicked : true});
        var topicsID = topicID;
    },

    render: function () {
        return (
            <div>
                <div className="row topic-list">
                    <SingleTopicBox 
                        topicID="1" 
                        onClick={this.onClick} 
                        label="Topic"
                        />
                    <SingleTopicBox 
                        topicID="2" 
                        onClick={this.onClick} 
                        label="Topic"
                        />
                    <SingleTopicBox 
                        topicID="3" 
                        onClick={this.onClick} 
                        label="Topic"
                        />
                    <SingleTopicBox 
                        topicID="4" 
                        onClick={this.onClick} 
                        label="Topic"
                        />
                </div>
                <div className="row">
                { this.state.isTopicClicked ? <SelectedTopicPage topicsID={topicsID} topicPages={topicPages} /> : null }
                </div>
            </div>
        );
    }
});
Ad

Answer

var is something which only exists in that (lexical) scope - i.e inside your onClick function (and any nested functions).

You should either assign it to this i.e. this.topicsID. Or, in this case it looks like you're better off setting it on the state as you want to re-render your child Component.

onClick = (topicID) => {
  this.setState({ topicsID });
},

render() {
   const { topicsID } = this.state;
   return (
     <div>
       {topicsID && <SelectedTopicPage topicsID={topicsID} topicPages={topicPages} /> }
     </div>
   );
}
Ad
source: stackoverflow.com
Ad