Reputation: 187
I have a search result component that contains a div that, when clicked, is supposed to open a modal. Here's the relevant code below:
const createClickableDiv = function(props){
if(props.searchType === 'option1'){
return (
<div onClick={this.onDivClick}>
<div>Some content</div>
</div>
);
}else if(props.searchType === 'option2'){
return (
<div onClick={this.onDivClick}>
<div>Some other content</div>
</div>
);
}
return (<div className="result-empty"></div>);
};
class SearchResultItem extends Component{
constructor(props){
super(props);
}
onDivClick(){
AppUIActions.openModal((<Modal />));
}
render(){
const clickableDiv = createClickableDiv(this.props);
return (
<div>
{clickableDiv}
</div>
}
}
When I load the page, nothing shows up. However, when I remove onClick={this.onDivClick}
from the divs, everything renders correctly, just without the desired click functionality. I put a try-catch around the code in the createClickableDiv function and it's saying this
is undefined. I'm not really sure where to go from here.
Thanks!
Upvotes: 1
Views: 92
Reputation: 14101
this.
sometimes behaves strangely. When your function createClickableDiv is called, this
no longer refers to your SearchResultItem but to the createClickableDiv, which does not have the function onDivClick defined.
Try changing the function call to createClickableDiv(this)
, to pass pointer to your complete SearchResultItem,
and change the function itself to:
const createClickableDiv = function(caller){
if(caller.props.searchType === 'option1'){
return (
<div onClick={caller.onDivClick}>
<div>Some content</div>
</div>
// etc..
Maybe that would work.
Upvotes: 3