MiguelSlv
MiguelSlv

Reputation: 15113

Unable to use React.RefObject with typescript

I am porting this class module example to typescript but i can't set it right the definition of the object reference.

I defined the reference holder as:

private wrapperRef:React.RefObject<HTMLDivElement>

The original handler had to be changed so it uses current property, has this:

if (this.wrapperRef.current && !this.wrapperRef.current.contains(event.target)) {
  alert('You clicked outside of me!');
}

but this.wrapperRef.current always comes undefined.

What i am doing wrong?

Here my sandbox.

Upvotes: 2

Views: 685

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187034

You aren't creating or setting your ref properly. In a class component, you create the ref with React.createRef():

constructor(props) {
  super(props)
  this.wrapperRef = React.createRef<HTMLDivElement>()
}

And then assign its value by passing it directly to the ref property of some element.

render() {
  return <div ref={this.wrapperRef}>{this.props.children}</div>;
}

Now it should automatically set this.wrapperRef.current after the first render. You don't need the setWrapperRef method at all.

Sandbox

Upvotes: 1

Related Questions