Christian Benseler
Christian Benseler

Reputation: 8065

ReactJS: access components inside component "parent"

How do I access React components created inside a parent component?

Example, with this code:

var Widget = React.createClass({

    render: function() {

        return <div>{ this.props.widget_id }</div>
    }
});

var Column = React.createClass({

    onBtnClick: function() {
        console.log(this);
        //
    },
    render: function() {
        var widgets = [];
        for(var i=0; i<3; i++) {
            widgets.push(<Widget key={i} widget_id={i} />);
        }
        console.log(widgets);
        return <div>
            <button onClick={this.onBtnClick}>click me</button>
            {widgets}</div>;
    }
});

React.render(<Column />, document.getElementById('container'));

console.log(widgets); gives me this, the 3 widgets created:

[ReactElement, ReactElement, ReactElement]

Inside the onBtnClick function, how do I access them? If I inspect "this" inside the function, either props and refs array are null ([]);

Here's a fiddle: https://jsfiddle.net/chrisbenseler/m8x9f65o/1/

Upvotes: 2

Views: 835

Answers (2)

J. Mark Stevens
J. Mark Stevens

Reputation: 4945

Handle the click in the child component using the parents handler passed as a prop. I changed the widget_id to just id because I know the event.target references the id. Havn't tried it with other attributes.

    var Widget = React.createClass({

            render: function() {

                    return <div onClick={this.props.onBtnClick}>{ this.props.id }</div>
            }
    });

    var Column = React.createClass({

            onBtnClick: function(ev) {
                    console.log(ev.target.id);
                    //
            },
            render: function() {
                    var widgets = [];
                    for(var i=0; i<3; i++) {
                            widgets.push(<Widget key={i} id={i}  onBtnClick={this.onBtnClick} />);
                    }
                    console.log(widgets);
                    return <div>
                            <button>click me</button>
                            {widgets}</div>;
            }
    });

    React.render(<Column />, document.getElementById('container'));

Upvotes: 1

Ed Ballot
Ed Ballot

Reputation: 3485

Add ref tag to the child, like this (I just added "widget" to give the example more depth, but it just has to be unique)

widgets.push(<Widget key={i} ref={"widget"+i} widget_id={i} />);

Then your parent accesses the component using this.refs like so

var secondWidget = this.refs.widget1;

You can read more about refs here https://facebook.github.io/react/docs/more-about-refs.html

Upvotes: 2

Related Questions