user8321027
user8321027

Reputation:

How to strongly type ref from an external component using typescript and react

I would like strongly type a ref component, but I cant do it and refference it like a component

I think my problem is in export of class. Is there an way to export class and this be recognized like a component and a class type at same time?

Class where I tried strongly type the ref

import EventsDropdown from "./events-dropdown";

type ExternalProps = {
    id?: string;
    name?: string;
    observations: IObservacao[];
    disabled: boolean;
    showLabel?: boolean;
    onChange?: (args?: any) => void;
    eventId?: number;   
};


class ParticipantObservations extends React.Component<ExternalProps, InternalState> {
    refs: {
        event: EventsDropdown //Didnt recognized like a type
    }
...

    render() {
        return <div>
            {/* works fine like a component */}
            <EventsDropdown name="eventId" showLabel disabled={false} ref={c => this.refs.event = c} />
        </div>
    }

}

The component EventsDropdown with export in the end of the code

...

class EventsDropdown extends React.Component<InternalProps & ExternalProps, {}> {
    componentWillMount() {
        this.props.getEvents();
    }

    public selectedText: string;

    render() {    
        return <select id={this.props.id} name={this.props.name} className="form-control" onChange={(e) => { this.props.onChange; this.selectedText = e.currentTarget.options[e.currentTarget.selectedIndex].text }} value={this.props.value} disabled={this.props.disabled} >
            <option value="">{this.props.showLabel ? "Evento" : ""}</option>
            {this.props.result.map(item => <option key={item.key} value={item.key}>{item.value}</option>)}
        </select>;
    }
}

export default connect<{}, {}, ExternalProps>(
    (state: ApplicationState) => state.lookup.events,
    actionCreators
)(EventsDropdown);

Upvotes: 2

Views: 606

Answers (1)

user9275636
user9275636

Reputation:

You are exporting/importing the result of calling connect and functions do not return types.

refs: { event: typeof EventsDropdown }

That should do it

Upvotes: 1

Related Questions