How are "refs" handled in Preact?
Asked Answered
H

2

11

React has the concept of refs. Is there a similar concept in Preact that can be used without preact-compat?

I want to be able to reference elements in Component methods without a DOM look-up.

Thanks!

Hayfield answered 15/9, 2017 at 20:38 Comment(0)
P
17

Instead of passing a string, you will pass a function. For example, you would render a component with ref as follows.

<Slideshow ref={slideshow => this.slideshow = slideshow} />

This means that you can now access it with this.slideshow.

Planoconvex answered 23/9, 2017 at 16:38 Comment(1)
This is how it works in React now, too - string refs have been deprecated.Adan
A
2

As of Feburary 2016, the core Preact package supports callback refs, so you should be able to follow along with the docs that you linked.

One thing that is explicitly not supported in the core library is string refs. They have been deprecated in React for a while now and are likely to be removed, so Preact didn't implement them to begin with. If you have a need for string refs (you probably don't, unless you're using an old third party library), preact-compat supports them.

For more info, see issue #50 on Preact's GitHub.

Adan answered 21/9, 2017 at 14:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.