nytimes / react-tracking

🎯 Declarative tracking for React apps.
https://open.nytimes.com/introducing-react-tracking-declarative-tracking-for-react-apps-2c76706bb79a
Other
1.88k stars 123 forks source link

Decorate class method passed to child component #109

Closed cpprookie closed 4 years ago

cpprookie commented 5 years ago

Thanks for your wonderful plugin.

After reading readMe, I wonder how to decorate class methods passed to childComponent as event handler with params.

For example. I get class component Wrapper

class Wrapper extends Component  {
    state: {
        tabIndex: 0,
         buttons: [1,2,3],
     }
    switchTab(index) {
        this.setState({ tabIndex: index })
    }
    render() {
       return <Tabs clickHandler={this.swtichTab.bind(this)} } />
    }
}

And it contains several buttons

({ buttons, switchTab}) => (
    <div>
        buttons.map((b, index) => <button onclick={() => { switchTab(index) }}>{b}</button>)
    </div>
)

Is there a way to track index param for decorated switchTab param?

tizmagik commented 5 years ago

You should be able to just decorate switchTab, you will have access to the args that the switchTab function is called with, or you can use the state arg. This is explained here in the README.

The signature when decorating (synchronous) class methods is:

@track((props, state, args) => {})

Returning an object will dispatch a tracking event.

For example (using the arg passed into switchTab):

@track() // this is necessary so decorating class method works
class Wrapper extends Component  {
    state: {
        tabIndex: 0,
         buttons: [1,2,3],
     }

    @track((props, state, [index]) => ({ event: 'tab-switch', index }))
    switchTab(index) {
        this.setState({ tabIndex: index })
    }
    render() {
       return <Tabs clickHandler={this.swtichTab.bind(this)} } />
    }
}
cpprookie commented 5 years ago

@tizmagik thanks for your clear answer :) I should read more carefully for the example in readme! And I will recommend this module to my teammate after personal use. By the way, I think examples in the sandbox should show this case to make users clear at first glance. Or create example files in module directory is much better? I could offer a pr if you think it is helpful.

tizmagik commented 5 years ago

Thanks @cpprookie -- yes a PR would be greatly appreciated. I plan on creating some kind of "common patterns" doc for more detailed examples, as you suggested, so you can link your PR to this issue: https://github.com/NYTimes/react-tracking/issues/86

Cheers!

cpprookie commented 5 years ago

Ok. I will do some work on this weekend. Cheers!