Anthony Kong
Anthony Kong

Reputation: 40624

Unable to set ref due to error "TS2339: Property 'X' does not exist on type 'Y' " inside a react component

Using TypeScript, I have the following props type and component class defined:

type AnimatedElementProps = {
  node: HTMLElement;
  Svg(props: SVGProps): JSX.Element,
 };

class AnimatedElement extends React.Component<AnimatedElementProps> {

  constructor(props) {
    super(props);
    this.node = undefined;
  }

  render = () => {
    return (
          <div
              ref={(n) => this.node = n}
              className={styles.animatedElement}
              style={defaultStyle}
          >
            <Svg/>
          </div>
    );
  };
}

I want to capture the ref to the div element inside the render function, however I keep getting:

error TS2339: Property 'node' does not exist on type 'AnimatedElement'.

What is the proper way to define and initialise a custom class variable inside a react component using TypeScript?

Upvotes: 1

Views: 1201

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

If I understand your question correctly then this looks like a case of a missing field in your class definition. You should find that declaring the field:

private node?: HTMLElement;

in your class definition resolves the issue:

class AnimatedElement extends React.Component<AnimatedElementProps> {

  private node?: HTMLElement; /* <-- Add this */

  constructor(props) {
    super(props);
    this.node = undefined;
  }

  render = () => {
    return (
          <div
              ref={(n) => this.node = n}
              className={styles.animatedElement}
              style={defaultStyle}
          >
            <Svg/>
          </div>
    );
  };
}

Also note, the node? syntax with question mark. The ? is short hand stating that the field can have type HTMLElement or undefined. This is necessary, seeing that you're initially assigning undefined to the field in your class constructor.

Upvotes: 2

Related Questions