'PrimeReact menu not compiling
I'm trying to have a PrimeReact popup menu working following the documention.
I created a new project with tsx.
I tried
import 'primereact/resources/themes/saga-blue/theme.css'
import 'primereact/resources/primereact.min.css'
import 'primeicons/primeicons.css'
import {Menu} from "primereact/menu";
import {useRef} from "react";
const Header = () => {
let menu = useRef(null);
let items = [
{icon: 'pi pi-cog', label: 'Configuration'},
{icon: 'pi pi-info-circle', label: 'About'}
];
return(
<div className="header">
<div><i className="pi pi-chevron-left"></i></div>
<div>Test</div>
<Menu model={items} popup ref={menu} id="popup_menu" />
<div><i className="pi pi-ellipsis-v" onClick={(event) => menu.current.toggle(event)} aria-controls="popup_menu" aria-haspopup/></div>
</div>
);
}
export default Header
When compiling it gives me
Object is possibly 'null'. TS2531
19 | <div>Test</div>
20 | <Menu model={items} popup ref={menu} id="popup_menu" />
> 21 | <div><i className="pi pi-ellipsis-v" onClick={(event) => menu.current.toggle(event)} aria-controls="popup_menu" aria-haspopup/></div>
| ^
22 | </div>
23 | );
24 | }
What am I missing ?
I also tried creating a new project with jsx instead of tsx.
And it is working. So the problem is coming from tsx.
But why ? And how to solve it ?
I eventually found a solution
use
let menu = useRef`<Menu>`(null);
and
onClick={(event) => menu?.current?.toggle(event)}
Solution 1:[1]
I was having this issue today. The solution from OP confused me a lot. I copy pasted exactly what OP posted which is:
let menu = useRef`<Menu>`(null);
and that does not work. I'm not entirely sure if this worked for OP or what, but the solution for me is to use the following:
let menu = useRef<Menu>(null);
My menu component looks like this:
<Menu model={menuItems} popup ref={menu} aria-controls="popup_menu" aria-haspopup />
And my button to show the menu looks like this:
<Button icon="pi pi-bars" onClick={(event) => menu.current?.toggle(event)}/>
If anyone is copy-pasting this to test, i used the following for menuItems:
const menuItems = [
{label: 'New', icon: 'pi pi-fw pi-plus'},
{label: 'Delete', icon: 'pi pi-fw pi-trash'}
];
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nemesis |
