I have a Modal in Component A and I want to show up that Modal by clicking on a button in component B.
I used the ref keyword but it doesn't work with this console error
"TypeError: Cannot destructure property 'toggleModal' of 'object null' as it is null."
A.js:
export class LoginForm extends Component{
constructor(props){
super(props);
this.state ={
isModalOpen: false
}
this.toggleModal = this.toggleModal.bind(this);
};
toggleModal(){
this.setState({
isModalOpen: !this.state.isModalOpen
})
};
render(){
return(
<Modal isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
<ModalHeader toggle={this.toggleModal}>Login</ModalHeader>
<ModalBody>
...
</ModalBody>
</Modal>
)
}
B.js:
import { LoginForm } from './FormsComponent';
class Header extends Component{
constructor(props){
super(props);
};
loginModalRef = ({toggleModal}) =>{
this.showModal = toggleModal;
};
onLoginClick = () =>{
this.showModal();
}
render(){
return(
<Nav className="ml-auto" navbar onClick={this.onLoginClick}>
<NavItem>
<Button outline color="primary">
<span className="fa fa-sign-in fa-lg"> Login</span>
</Button>
</NavItem>
</Nav>
<LoginForm ref={this.loginModalRef} />
)}}
UPDATE QUESTION: This way works perfectly with me, I discovered the Error message was due another issue in my code. So guys you can take this as a solution if you wanna do the same thing.