'Exporting functions with React TypeScript
The Setup
I have a sidebar component that opens and closes when the user clicks a button...
/* Sidebar.tsx */
export function PersistentDrawerLeft(){
const [open, setOpen] = React.useState(false)
const [sidebarText, setSidebarText] = React.useState('')
const handleDrawerOpen = (sidebarText) => {
setSidebarText(sidebarText)
setOpen(true)
}
const handleDrawerClose = () => {
setOpen(false)
setSidebarText('')
}
}
I would like to export the handleDrawerOpen/Close functions so that other components can control the sidebar, and tell the sidebar what to display.
Where it will be used
Namely, when a user clicks in an input, the sidebar opens with comments about the field. Something like this:
/* MyForm.tsx. */
<TextField
id="make"
label="Make"
data-sidebarText="The make of the car, ie: Ford, Chevy, etc."
onClick={handleDrawerOpen(this.data-sidebarText)}
onFocusOut={handleDrawerClose()}
value={make}
/>
The Problem
The problem is the linter doesn't like my export decorator. As seen above, it says Modifiers cannot appear here (inside the function I assume).
When I try to move these outside of the function that error goes away, but then it has a problem with useState. It says React.useState cannot be called at the top level...`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
