1

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.

Anis
  • 77
  • 2
  • 7
  • 1
    Please don't try to defeat the minimum length filter - there is always more you can write. "Doesn't work" is a bit vague - what is your result when you try this? Any console errors? – halfer Aug 09 '20 at 16:57

3 Answers3

0

using state management is a good practice, otherwise refs can help you for this, you can access component A functions to component B.

Amit Shakya
  • 962
  • 3
  • 16
  • 30
0

You can move the state 'up' to a parent component that contain both the LoginForm and Header. and pass the callback and the state to both compoennts

    class Parent {
    state = { modalOpen: false }
    openModal = ()=> setState({modalOpen: true})
render(){
return <div>
    <Header onClick={openModal} />
    <LoginForm modalOpen={modalOpen} />
</div>
}
}
nachmo
  • 144
  • 5
  • I want a reusable Modal because I'm going to use this Modal with other components in order to avoid creating the same Modal again – Anis Aug 09 '20 at 22:57
0

To handle the modal state from child, I used this solution https://stackoverflow.com/a/71464748/1770571 and it works properly with me

Salma Gomaa
  • 952
  • 1
  • 13
  • 18