Reputation: 1
I work on a project which use "react-notification-alert" from creativetim. In their doc they show an example to use their alert. This works basicly with this.ref but I know that is depreciated, so I tried to replace it by using createRef() like below:
class App extends Component {
constructor(props);
this.notifRef = React.createRef();
myFunc(){
this.notifRef.current.notify.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={this.notifRef} />
<button onClick={() => this.myFunc()}>Hey</button>
</div>
);
}
}
But problem is that the console show me
Cannot read property 'notificationAlert' of undefined
I tried many solution, and saw a lot of answer on stack, but I have difficulties to understand how it could works.
Thanks for your help !
Upvotes: 0
Views: 872
Reputation: 167
Try this:
class App extends Component {
constructor(props){
super();
this.myFunc = this.myFunc.bind( this );
}
myFunc(){
this.notifRef.current.notify.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={ e=> this.notifRef = e } />
<button onClick={ this.myFunc }>Hey</button>
</div>
);
}
}
Upvotes: 0
Reputation: 2272
The main difference between string constants and createRef is createRef stores data in current
field, as string constant stores it in this.refs[stringConstant].
So your code could be:
class App extends Component {
constructor(props) {
this.notifRef = React.createRef();
}
myFunc(){
this.notifRef.current.notificationAlert(options);
}
render() {
return (
<div>
<NotificationAlert ref={this.notifRef} />
<button onClick={() => this.myFunc()}>Hey</button>
</div>
);
}
}
Upvotes: 2