Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure object containing functions?

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?

like image 964
grazianodev Avatar asked Jun 07 '26 06:06

grazianodev


1 Answers

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} ...
like image 181
jo_va Avatar answered Jun 10 '26 17:06

jo_va