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?
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.
Most helpful comment
Yup, the former snippet is still the way to go for now. The changes to
createElementhaven't progressed past a proposal yet.