SolidJS bindings for Floating UI. Based on
@floating-ui/react-dom
npm install --save @floating-ui/dom solid-floating-ui
yarn add @floating-ui/dom solid-floating-ui
pnpm add @floating-ui/dom solid-floating-ui
import { createSignal } from 'solid-js';
import { useFloating } from 'solid-floating-ui';
function App() {
const [reference, setReference] = createSignal();
const [floating, setFloating] = createSignal();
// `position` is a reactive object.
const position = useFloating(reference, floating);
return (
<>
<button ref={setReference}>Button</button>
<div
ref={setFloating}
style={{
position: position.strategy,
top: position.x ?? 0,
left: position.y ?? 0,
}}
>
Tooltip
</div>
</>
);
}
position
is based on computePosition
's return value has the following fields:
x
andy
are the positioning coords. Initial values are null.strategy
is eitherabsolute
(default) orfixed
. Refer tostrategy
optionplacement
is refers to theplacement
options
Middlewares can also be used:
import { useFloating } from 'solid-floating-ui';
import { offset, flip, shift } from '@floating-ui/dom';
const [reference, setReference] = createSignal();
const [floating, setFloating] = createSignal();
useFloating(reference, floating, {
placement: 'right',
strategy: 'fixed',
middleware: [offset(10), flip(), shift()],
});
useFloating()
only calculates the position once on render, or when the reference/floating elements changed — for example, the floating element gets mounted via conditional rendering.
If the floating element lives in a different offsetParent
context to the reference element, it will need to be updated while mounted to remain “anchored”. This includes scrolling and resizing the window or the elements themselves.
To do so, use the autoUpdate
utility:
import { useFloating } from '@floating-ui/react-dom';
import { autoUpdate } from '@floating-ui/dom';
function App() {
const [reference, setReference] = createSignal();
const [floating, setFloating] = createSignal();
useFloating(reference, floating, {
whileElementsMounted: autoUpdate,
// Or, pass options. Ensure the cleanup function is returned.
whileElementsMounted: (reference, floating, update) => (
autoUpdate(reference, floating, update, {
animationFrame: true,
}),
)
});
}
Alternatively (or additionally), you may want to update manually in some cases. The primitive returns an update()
function to update the position at will:
const position = useFloating();
position.update();
See Virtual Elements for details.
function App() {
const [floating, setFloating] = createSignal();
const position = useFloating(
() => ({
getBoundingClientRect() {
return {
// ...
};
},
}),
floating,
);
return (
<div
ref={floating}
style={{
position: position.strategy,
top: position.y ?? 0,
left: position.x ?? 0,
}}
>
Tooltip
</div>
);
}
MIT © lxsmnsyc