Reputation: 141
I'm fairly new to Typescript and React. I've been trying to implement the react-rewards
npm library and I have solved all except one issue.
type Props = {}
class Surprisebutton extends Component<Props>{
reward: any;
render() {
return (
<Reward
ref={(ref) => { this.reward = ref }}
type='memphis'>
<Button onClick={this.reward.rewardMe()} style={styles.button} variant="contained" color="primary">
Surprise!
<FavoriteIcon style={{ marginLeft: 10 }} />
</Button>
</Reward>
)
}
}
After running npm start
I get an error which says TypeError: this.reward is undefined
. What is the best way to resolve?
Upvotes: 2
Views: 1534
Reputation: 703
Change your onClick
to something like this:
onClick={() => {this.reward.rewardMe()}}
Upvotes: 0
Reputation: 7545
It has nothing to do with TypeScript. TS is only a compiler and linter and you're getting a runtime error. It's this line:
this.reward.rewardMe()
The ref
gets assigned after the component fully mounts and rewardMe()
is attempting to call it immediately. This is also a secondary mistake. You don't want to use the ()
invocation or the function is going to immediately fire (and never stop).
The line should be
<Button onClick={this.reward.rewardMe} style={styles.button} variant="contained" color="primary">
Upvotes: 1
Reputation: 3642
I might be wrong because I never used this package but according to documentation/Useage topic. They are not initializing reward
variable. Try removing that, Here's the fixed version
type Props = {}
class Surprisebutton extends Component<Props>{
render() {
return (
<Reward
ref={(ref) => { this.reward = ref }}
type='memphis'>
<Button onClick={this.reward.rewardMe()} style={styles.button} variant="contained" color="primary">
Surprise!
<FavoriteIcon style={{ marginLeft: 10 }} />
</Button>
</Reward>
)
}
}
Again I might be wrong but according to the github page i thinks that's the only thing i can infer.
Upvotes: 0