Holiday Notice: Support will be provided on a limited scale from December 24th, 2024, to January 2nd, 2025. Happy holidays and a wonderful New Year!


Topic: Modal react hooks support

gllermaly free asked 5 years ago


*Expected behavior*Modal to work with props/react hooks

*Actual behavior*Infinite loop

Resources (screenshots, code snippets etc.)

function Providers(props) {
  const [toggle, setToggle] = useState(props.toggle);
  return (
    <MDBContainer>
      <MDBModal isOpen={toggle}>
        <MDBModalHeader>XX</MDBModalHeader>
        <MDBModalBody>(...)</MDBModalBody>
        <MDBModalFooter>
          <MDBBtn color="secondary" onClick={setToggle(false)}>
            Close
          </MDBBtn>
        </MDBModalFooter>
      </MDBModal>
    </MDBContainer>
  );
}

I can open the modal but not close it (when I add the code the infinity loop error appears).


Jakub Chmura staff answered 5 years ago


Hi @gllermaly

Your component falls into an infinite loop because you call setToggle without function. You should use a function that will be called after click to change the state.

Please check this snippet. It should work:

function Providers(props) {
  const [toggle, setToggle] = useState(false);

  return (
    <MDBContainer>
      <MDBModal isOpen={toggle}>
        <MDBModalHeader>XX</MDBModalHeader>
        <MDBModalBody>(...)</MDBModalBody>
        <MDBModalFooter>
          <MDBBtn color='secondary' onClick={() => setToggle(false)}>
            Close
          </MDBBtn>
        </MDBModalFooter>
      </MDBModal>
    </MDBContainer>
  );
}

Let me know if my solution works with this matter.

Best regards,

Kuba


Hasi@14751033 free commented 4 years ago

hello please can you suppose a way to make toggleCollapse work inside the navbar when using useState hook instead of class based navbar component


Piotr Glejzer staff commented 4 years ago

which toggleCollapse do you talking about?



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 4.22.1
  • Device: macbook pro
  • Browser: chrome
  • OS: macos mojave
  • Provided sample code: No
  • Provided link: No