da coconut
da coconut

Reputation: 863

Type 'void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

what happened to me, can u tell me what 2 do?

I am creating a website that needs hooks to replace the state. I am on my index.js. the error is on the onClicks inside the divs inside the Menu. Menu comes from material-UI

My code:

import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';

export default function SimpleMenu() {
    const [ anchorEl, setAnchorEl ] = React.useState<null | HTMLElement>(null);
    const [ language, setLanguage ] = useState('English');
    const languages = [ 'English', 'Chinese ( Simplified )', 'Chinese ( Traditional )' ];

    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = (word: string) => {
        setLanguage(word);
    };

    return (
        <div>
            <Button aria-controls="simple-menu" aria-haspopup="true" onClick={handleClick}>
                Open Menu
            </Button>
            <Menu id="simple-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>
                <div onClick={handleClose(languages[0])}>{languages[0]}</div>
                <div onClick={handleClose(languages[1])}>{languages[1]}</div>
                <div onClick={handleClose(languages[2])}>{languages[2]}</div>
            </Menu>
        </div>
    );
}


----------


error:

```Type 'void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'.```

can u please help me?

( bottom is gibberish )



Upvotes: 0

Views: 19507

Answers (2)

Ali Bayatpour
Ali Bayatpour

Reputation: 448

Hey hope this solves your problem: First write the onClick on your button like this:

    <Button
      aria-controls="simple-menu"
      aria-haspopup="true"
      onClick={() => handleClick(event as MouseEvent)}
    >
      Open Menu
    </Button>

Then write your handleClick like this:

    const handleClick = (event: MouseEvent) => {
    setAnchorEl(event.currentTarget);
};

Might not be the best solution but I think it solves your problem :)

Upvotes: 1

Sargis Isoyan
Sargis Isoyan

Reputation: 1089

Change onClick={handleClose(languages[0])} into arrow function like this

onClick={() => handleClose(languages[0])}

Or change handleClose function

const handleClose = () => (word: string) => {
    setLanguage(word);
};

Upvotes: 7

Related Questions