Morgan Allen Morgan Allen - 9 days ago 5
React JSX Question

Creating onClick event in React

I am trying to create a table and render some rows with the ability to have a "hidden" row.

Here is what I'm trying to do:

var Child = React.createClass({
render: function() {
return(
<tr>
<td colSpan="8"> I am a child that can be hidden!</td>
</tr>
)
}
})


var CreateRows = React.createClass({
getInitialState: function() {
return {childVisible: true}
},

render: function(){
var rows = this.props.people.map(function(row, i){
return (
<tr key={i} onClick={this.onClick}>
<td>{row['id']}</td>
</tr>
{
this.state.childVisible
? <Child />
: null
}
)
})
return (
<tbody>
{rows}
</tbody>
)
},

onClick: function(){
this.setState({childVisible: !this.setstate.childVisible})
}
});


I am calling
CreateRows
in another component and sending it some data:

render: function(){
return (
<div>
<ChangeRowCount updatePeople = {this.updatePeople}/>
<table>
<CreateColumns columns={this.state.table_columns} />
<CreateRows people = {this.state.people}/>
</table>
</div>
)
}


I realize my issue is that when I create the variable
rows
I'm including the function
onClick()
but it can't "see" it and getting this error:

Uncaught (in promise) TypeError: Cannot read property 'onClick' of undefined(…)


Any thoughts on how I can include the onClick() function to show/hide the
Child
component?

Thanks!

Answer

youre seeing this error because you're calling this.onClick inside of the map function. you need to set the context of the map function by passing this in as the second argument

    var rows = this.props.people.map(function(row, i){
        return (
            <tr key={i} onClick={this.onClick}>      
                <td>{row['id']}</td>
            </tr>
            {
                this.state.childVisible
                ? <Child />
                : null
            }
        )
    }, this)

see the thisArg section from the documentation on the map function