Preact: forwardRef in Preact

Created on 8 Apr 2019  路  5Comments  路  Source: preactjs/preact

I have a Sidebar component with number images. I have in my App.js sections of a webpage. I would like to click the number image to scroll to that section of my webpage. For example, I click on number image 5, webpage scrolls to section 5.

The onclick action is in my Sidebar component. And I imported the Sidebar component into App.js. I created refs in my App.js. How do I access the parent's refs?

Most helpful comment

Yup, the former snippet is still the way to go for now. The changes to createElement haven't progressed past a proposal yet.

All 5 comments

Preacr/compat has forwardRef and in normal preact you can pass it through to your Child in props.

To elaborate on that a bit: We decided to put forwardRef into preact/compat instead of our core because in the future forwardRef will likely not be needed anymore. The reason it exists is because virtual-dom libraries filter out the ref from props when a Component is created. If it would be left on props we could just use that.

It would effectively change the current situation from this:

import { h } from "preact";
import { forwardRef } from "preact/compat";

// Some high-order component
function withLog(Wrapped) {
  return forwardRef((props, ref) => {
    return (
      <Foo>
        <Bar>
          <Wrapped {...props} ref={ref} />
        </Bar>
      </Foo>
    );
  };
}

to this:

// not possible today, but hopefully soon
import { h } from "preact";

// Some high-order component
function withLog(Wrapped) {
  return props => (
    <Foo>
      <Bar>
        <Wrapped {...props} />
      </Bar>
    </Foo>
  )};
}

which is a lot shorter and easier to understand. We're hoping that we can tackle the latter after Preact X went gold. For now the former snippet is the way to go :+1:

Thank you both for your quick response! This was very helpful! :)

@marvinhagemeister, would the former example still work with Preact X?

Yup, the former snippet is still the way to go for now. The changes to createElement haven't progressed past a proposal yet.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jescalan picture jescalan  路  3Comments

adriaanwm picture adriaanwm  路  3Comments

youngwind picture youngwind  路  3Comments

rajaraodv picture rajaraodv  路  3Comments

paulkatich picture paulkatich  路  3Comments