Bolboa Bolboa - 12 days ago 7
React JSX Question

How to use parent function inside react's map function

I'm passing the following functions to the following component...

<Main css={this.props.css} select={this.selectedCSS.bind(this)} save={this.saveCSS.bind(this)} />


Then inside the
Main
component I am using these functions...

<h1>Select the stylesheet you wish to clean</h1>
{
this.props.css.map(function(style){

if (style) {
return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>)
}
})
}

</div>
<button className="cleanBtn" onClick={this.props.save}>Clean!</button>


Notice in my
map
function, I am passing
this.props.select(style)
. This is a function from the parent, and I am trying to pass to it a parameter. But when I do this, I get an error...

Error in event handler for runtime.onMessage: TypeError: Cannot read property 'props' of undefined


Every other function I pass works. I've already tested them. In fact, the code works, the only issue is when I try to pass a function inside
map
. What is the reason for this? How can I fix it?

I tried to add
.bind(this)
but it runs in an infinite loop when I do so.

Answer

In your mapping function, this does no longer point to the react component.

Bind the context manually to resolve this:

{
    this.props.css.map((function(style) {
        if (style) {
            return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>)
        }
    }).bind(this))
}

Alternatively, use an ES6 arrow function, which preserves the surrounding context:

{
    this.props.css.map(style => {
        if (style) {
            return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>)
        }
    })
}
Comments