owl
owl copied to clipboard
useEffect that depends on a reference element inside a slot
export function useAutofocus() {
const comp = useComponent();
const ref = useRef("autofocus");
useEffect(
(el) => {
if (el) {
el.focus();
}
},
() => [ref.el]
);
return ref;
}
class App extends owl.Component {
static template = owl.xml`
<Dropdown>
<t t-set-slot="toggler">
Show menu on hover // - imagine when hovered here, the "menu" element below will be shown.
</t>
<div class="menu">
<input t-ref="autofocus" />
<Items />
<div>
</Dropdown>
`
setup() {
this.inputRef = useAutofocus();
}
}
Carefully considering the code above, the first impression is that when the "menu" div is shown, it will automatically focus on the input element. However, that's not the case.
Since the displaying of the "menu" is controlled by the "Dropdown" component, the callback of the "useAutofocus" doesn't really trigger the first time the "menu" is displayed. Only when the "menu" repatches, that the autofocus will be triggered.
- Upon showing this to GED, he thought of introducing "useCallbackRef" (can't remember the full details of the reasoning).
- Perhaps we can have something like render props where state of the Parent component can be passed thru it's sub component/elements. I believe this pattern is done in react.