Reputation: 538
When I try to call the Modal component I'm getting this error -
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
- You might have mismatching versions of React and the renderer (such as React DOM)
- You might be breaking the Rules of Hooks
- You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
How can I show this modal when pressing a button in functional component?
Thanks
Search.jsx
import AddedToCart from '../modals/Modal';
const Search=()=>{
return(
<div>
<button
onClick={() => AddedToCart()}
>
</div>
)
}
Modal.jsx
import Modal from 'react-bootstrap/Modal';
import React, { useState } from 'react';
export default function AddedToCart() {
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
return (
<>
<button variant='primary' onClick={handleShow}>
Launch demo modal
</button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Modal heading</Modal.Title>
</Modal.Header>
<Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body>
<Modal.Footer>
<button variant='secondary' onClick={handleClose}>
Close
</button>
<button variant='primary' onClick={handleClose}>
Save Changes
</button>
</Modal.Footer>
</Modal>
</>
);
}
Any help will be awesome.
Upvotes: 1
Views: 1207
Reputation: 28654
onClick={() => AddedToCart()}
You are calling it like a function in a click handler, that is not how you render stuff in react.
instead set a flag
onClick={() => setOpenModal(true)}
and then in render
{openModal && <AddedToCart/>}
Upvotes: 2