I have the following React component:
import { AppInterface } from 'pages/_app'
export default class SiteNavBtn extends React.Component {
static contextType = AppInterface
render() {
const { actions } = this.context
const { toggleSiteNav } = actions || {}
return(
<button className="site-nav-btn" onClick={ () => toggleSiteNav() }>
<i className="icon"><span>Open menu</span></i>
</button>
)
}
}
With the above code, if this.context is undefined and I click on the button, an error complains that toggleSiteNav is not a function (as expected), so I have set an empty function as a default value for it:
const { actions } = this.context
const { toggleSiteNav = () => {} } = actions || {}
This works, meaning that if this.context is undefined, when I click on the button now nothing happens of course but I don't get an error, however I believe I am invoking an empty function. Is this correct or is there a better way to destructure an object that contains functions and that may be undefined?
onClick={toggleSiteNav}in this case.onClick={ () => toggleSiteNav() }can be writte asonClick={toggleSiteNav}