Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are "refs" handled in Preact?

Tags:

preact

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!

like image 794
Donald Taylor Avatar asked Sep 15 '17 20:09

Donald Taylor


2 Answers

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.

like image 186
Joe Clay Avatar answered Oct 24 '22 06:10

Joe Clay


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.

like image 26
Daniel Apt Avatar answered Oct 24 '22 04:10

Daniel Apt