Kaushik
Kaushik

Reputation: 1349

Passing method as props to all children

Trying to pass the method as props to all children. But on printing the child props in console it is showing undefined.

Console output:

Object {openLightbox: undefined, closeLightbox: undefined, setLightboxState: undefined, key: 0}   

Passing openLightbox, closeLightbox and setLightboxState methods as props to the all the children. Setting it in variable childProps.

var Lightbox = React.createClass({

    getInitialState: function(){
        return { display: false };
    },

    componentWillMount: function(){
        if (this.props.data)
            this.setState(this.props.data);
    },

    openLightbox: function(){
        this.setState({display: true});
    },

    closeLightbox: function(){
        this.setState({display: false});
    },

    setLightboxState: function(obj){
        this.setState(obj);
    },

    render: function(){
        var childrenWithProps = this.props.children.map(function(child, i) {
            var childProps = {
                openLightbox: this.openLightbox,
                closeLightbox: this.closeLightbox,
                setLightboxState: this.setLightboxState,
                key: i
            };
            console.log(childProps)
            for (var j in this.state){
                childProps[j] = this.state[j];
            }

            var childWithProps = React.cloneElement(child, childProps);

            return childWithProps;
        });

        return (
            <div>
                {childrenWithProps}
            </div>
        );
    }
});

Upvotes: 2

Views: 432

Answers (2)

Roman Yakobchuk
Roman Yakobchuk

Reputation: 22

Fitst of all you should not iterate over this.props.children directly, React has a top-level API for mapping over this.props.children(https://facebook.github.io/react/docs/top-level-api.html).

Then function inside map will have window or undefined as this, so you should use arrow function(=> in ES2015) or .bind(this) to link React Component instance to this

var childrenWithProps = React.Children.map(this.props.children, function(child) { ... }.bind(this))

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

this in .map refers to global scope(in browser it is window or undefined if you use strict mode) where there are no methods openLightbox, closeLightbox etc. You can set this for .map through second argument

this.props.children.map(function(child, i) {
  ...
}, this);
___^^^^_

Upvotes: 2

Related Questions