Search code examples
reactjstypescriptevent-handlingtsx

Make use of event handler in React Component for TSX tag


Is there a way to make an event handler defined within a React Component accessible in an HTML-like tag? What I mean is something like:

<MyComp param1="abc" param2="def" onDoSomething={this.someMethod} />

My goal is to define onDoSomething, but currently I only know how to create params such as param1 and param2.

export interface MyCompProps {
    param1: string;
    param2: string;
}

export interface DoSomethingEvent {
    someParam: string;
}

export class MyComp extends React.Component<MyCompProps, {}> {
    private doSomethingDispatcher = new EventDispatcher<DoSomethingEvent>();

    public onDoSomething(handler: Handler<DoSomethingEvent>) {
        this.doSomethingDispatcher.register(handler);
    }

    private fireDoSomething(param: string) {
        this.doSomethingDispatcher.fire({someParam: param});
    }
}

How can I make the event handler onDoSomething accessible via TSX, similar to making use of the onClick event?


Solution

  • You might be running into issues as you are not currently providing a function to onDoSomething, but the returned result:

    <MyComp param1="abc" param2="def" onDoSomething={this.someMethod()} />
    

    should be

    <MyComp param1="abc" param2="def" onDoSomething={this.someMethod} />