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?
That is correct, you could however write it like this:
const { actions: { toggleSiteNav = () => {} } = {} } = this.context;
...
<button onClick={toggleSiteNav} ...
Or simply not attach the handler if it is falsy:
const { actions: { toggleSiteNav } = {} } = this.context;
...
<button onClick={toggleSiteNav ? toggleSiteNav : null} ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With