Reputation: 3815
I'm opening modal from another component by using ref in reactjs. for that I'm doing below code.
otpModalRef = ({onOpenModal}) => {
this.showModal = onOpenModal;
}
and in render below code
<div className="otp_modal">
<Otp ref={this.otpModalRef} ></Otp>
</div>
& then calling in register function by this.showModal();
It's working fine. but when I clicked on login button it's giving me TypeError: Cannot read property 'onOpenModal' of null
. Below is login and register functions.
login = (e) => {
e.preventDefault();
axios.post('/api/signin', {
user:this.state.user,
password:this.state.login_pass,
})
.then(res => {
console.log(res);
this.context.router.history.push({
pathname:'/',
});
})
.catch(function (error) {
console.log(error.message);
})
}
register = (e) => {
e.preventDefault();
axios.post('/api/user/add', {
firstname: this.state.fname,
lastname:this.state.lname,
email:this.state.emailaddress,
password:this.state.password,
mobile:this.state.mobile
},
)
.then(res => {
console.log(res);
this.showModal();
})
}
Not getting what is the issue? If I comment the otpModalRef
it redirects to homepage but if I keep the gives this null error.
Upvotes: 0
Views: 199
Reputation: 10334
You need to call React.createRef() to create a handle and not like you did in roure code.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.otpModalRef = React.createRef();
}
render() {
...
}
}
Upvotes: 2