noblerare
noblerare

Reputation: 11853

Refs with instance variable gives error

I have a React component that I'm migrating to tsx file and I'm getting an error Property 'name' does not exist on type 'NameComponent'.

Here is my component:

class NameComponent extends React.Component<NameComponentProps> {
    render() {
        return (
            <Modal>
                <Modal.Header>
                    Enter Name
                </Modal.Header>
                <Modal.Body>
                    <FormGroup>
                        <ControlLabel>Name: </ControlLabel>
                        <FormControl type="text"
                            placeholder='Enter name'
                            inputRef={(ref) => this.name = ref}
                            onChange={() => this.props.onValidate({ name: this.name.value })}
                        />
                        <FormControl.Feedback />
                    </FormGroup>
               </Modal.Body>
            </Modal>
        );
    }
}

There is a red undeline on the occurences of this.name. This worked back when I had this file in .js format.

How do I resolve this error?

Upvotes: 1

Views: 40

Answers (1)

Tholle
Tholle

Reputation: 112777

You can add a private class field on your component that will store the name HTMLInputElement.

class NameComponent extends React.Component<NameComponentProps> {
    private name: HTMLInputElement;

    render() {
        return (
            <Modal>
                <Modal.Header>
                    Enter Name
                </Modal.Header>
                <Modal.Body>
                    <FormGroup>
                        <ControlLabel>Name: </ControlLabel>
                        <FormControl type="text"
                            placeholder='Enter name'
                            inputRef={(ref) => this.name = ref}
                            onChange={() => this.props.onValidate({ name: this.name.value })}
                        />
                        <FormControl.Feedback />
                    </FormGroup>
               </Modal.Body>
            </Modal>
        );
    }
}

Upvotes: 1

Related Questions