Reputation: 2266
I had a functional React Component that looked like this:
import React from 'react';
const expand = (itemId) => {
alert('item ' + itemId + ' clicked!');
}
const Item = ({itemData: {id, title, thumbnail}}) => {
let hasThumb = !(thumbnail === 'self' || thumbnail === 'nsfw');
return (
<div className="item" onClick={() => expand(id)}>
<h3 className="item-title">{title}</h3>
<img className="item-thumbnail" src={hasThumb ? thumbnail: 'placeholder.png'}
alt={hasThumb ? 'Item thumbail' : 'Placeholder thumbnail'} />
</div>
);
};
export default Item;
It works perfectly! But I want to add functionality that will require me to make it stateful/change it to a class-based Component structure. I did it like this:
import React, {Component} from 'react';
class Item extends Component {
expand = (itemId) => {
alert('item ' + itemId + ' clicked!');
}
render() {
let hasThumb = !(this.props.itemData.thumbnail === 'self' || this.props.itemData.thumbnail === 'nsfw');
return (
<div className="item" onClick={() => this.expand(this.props.itemData.id)}>
<h3 className="item-title">{this.props.itemData.title}</h3>
<img className="item-thumbnail" src={hasThumb ? this.props.itemData.thumbnail: 'placeholder.png'}
alt={hasThumb ? 'Item thumbail' : 'Placeholder thumbnail'} />
</div>
);
};
}
export default Item;
It compiles perfectly with no errors, but in the browser I get TypeError: _ref is undefined
and it calls out the line number for the render definition. I found that removing the destructuring statement in the render argument makes this go away (I can refer to everything as this.props.data.[whatever]
) but this is inconvenient compared with being able to destructure, as I'm able to do in a functional React component. What have I done wrong here? Or is destructuring in this way simply not possible?
Upvotes: 0
Views: 2881
Reputation: 2483
In React, for class based component destructuring is done inside the method.
eg:
render() {
let { itemData: {id, title, thumbnail} } = this.props;
.....
}
componentDidMount() {
let { itemData: {id, title, thumbnail} } = this.props;
.....
}
Upvotes: 1