onClick open module

//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:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

Answer

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