//Home.js
import React from "react";
function Header() {
return (
<div className="header__search">
<ImageSearchIcon onClick = { Upload_img }/>
</div>
);
}
export default Header;
//Upload_img.js
import React, {useState} from "react";
import Modal from '@material-ui/core/Modal';
const Upload_img = (props) => {
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div>
<Modal
open={open}
onClose={handleClose}
><h1>hello</h1></Modal>
</div>
)
}
export default Upload_img
I would like to use modal as module But I am getting this kind of 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:
There can be multiple ways to solve this issue. I believe the easiest way is to move your modal state in the parent (Header) component.
//Home.js
import React from "react";
function Header() {
const [open, setOpen] = React.useState(false);
const handleOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div className="header__search">
<ImageSearchIcon onClick={handleOpen}/>
<Upload_img open={open} handleOpen={handleOpen} handleClose={handleClose} />
</div>
);
}
export default Header;
Now your Upload_img component will be a stateless component and it will look like this:
//Upload_img.js
import React from "react";
import Modal from '@material-ui/core/Modal';
const Upload_img = ({open, handleClose, handleOpen}) => {
return (
<div>
<Modal
open={open}
onClose={handleClose}
><h1>hello</h1></Modal>
</div>
)
}
export default Upload_img