mirror of
https://github.com/Dvorinka/Devour.git
synced 2026-06-04 20:43:05 +00:00
17 lines
8.2 KiB
JSON
17 lines
8.2 KiB
JSON
{
|
|
"id": "0732712dd1914959d7b3eb80",
|
|
"source": "solid:signals",
|
|
"type": "github-document",
|
|
"title": "refs",
|
|
"content": "---\ntitle: Refs\nuse_cases: \u003e-\n dom access, element references, focus management, third-party libraries,\n canvas manipulation, forwarding refs\ntags:\n - refs\n - dom\n - elements\n - directives\n - access\n - forward\nversion: '1.0'\ndescription: \u003e-\n Access and manipulate DOM elements directly using refs, forward refs between\n components, and create custom directives.\n---\n\nRefs, or references, are a special attribute that can be attached to any element, and are used to reference a DOM element or a component instance.\nThey are particularly useful when you need to access the DOM nodes directly or invoke methods on a component.\n\n## Accessing DOM elements\n\nOne way of accessing DOM elements is through [element selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors) such as [`document.querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) or [`document.getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById).\nSince elements in Solid can be added or removed from the DOM based on state, you need to wait until the element is attached to the DOM before accessing it.\nThis can be done by using [`onMount`](/reference/lifecycle/on-mount) to wait until the element is attached to the DOM before accessing it:\n\nAccessing DOM elements through element selectors is not recommended for this reason.\nAs elements with the same selectors are added and removed from the DOM, the first element that matches the selector will be returned, which may not be the element you want.\n\n## JSX as a value\n\nJSX can be used as a value and assigned to a variable when looking to directly access DOM elements.\n\n```tsx\nfunction Component() {\n\tconst myElement = \u003cp\u003eMy Element\u003c/p\u003e\n\n\treturn \u003cdiv\u003e{myElement}\u003c/div\u003e\n}\n```\n\nThis lets you create and access DOM elements similar to [`document.createElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) but without having to wait until it is attached to the DOM.\nIt can be used multiple times without having to worry about duplicate selectors.\n\nThe downside of this approach is that it separates the element and any child elements from the rest of the JSX structure.\nThis makes the component's JSX structure more difficult to read and understand.\n\n## Refs in Solid\n\nSolid provides a ref system to access DOM elements directly inside the JSX template, which keeps the structure of the elements intact.\n\nTo use [`ref`](/reference/jsx-attributes/ref), you declare a variable and use it as the `ref` attribute:\n\n```tsx {6}\nfunction Component() {\n\tlet myElement;\n\n\treturn (\n\t\t\u003cdiv\u003e\n\t\t\t\u003cp ref={myElement}\u003eMy Element\u003c/p\u003e\n\t\t\u003c/div\u003e\n\t)\n}\n```\n\nThese assignments occur at _creation time_ prior to the element being added to the DOM.\nIf access to an element is needed before it is added to the DOM, you can use the callback form of `ref`:\n\n```jsx\n\u003cp ref={(el) =\u003e {\n\tmyElement = el // el is created but not yet added to the DOM\n\t}}\u003e\n\tMy Element\n\u003c/p\u003e\n```\n\n:::note\nIn TypeScript, you must use a definitive assignment assertion.\nSince Solid takes care of assigning the variable when the component is rendered, this signals to TypeScript that the variable will be assigned, even if it can't\nconfirm it.\n\n```tsx\nlet myElement!: HTMLDivElement;\n```\n:::\n\n### Signals as refs\n\n[Signals](/concepts/signals) can also be used as refs.\nThis is useful when you want to access the element directly, but the element may not exist when the component is first rendered, or may be removed from the DOM at some point.\n\n```jsx\nfunction App() {\n\tconst [show, setShow] = createSignal(false)\n\tlet element!: HTMLParagraphElement\n\n\treturn (\n\t\t\u003cdiv\u003e\n\t\t\t\u003cbutton onClick={() =\u003e setShow((isShown) =\u003e !isShown)}\u003eToggle\u003c/button\u003e\n\n\t\t\t\u003cShow when={show()}\u003e\n\t\t\t\t\u003cp ref={element}\u003eThis is the ref element\u003c/p\u003e\n\t\t\t\u003c/Show\u003e\n\t\t\u003c/div\u003e\n\t)\n}\n```\n\nIn this example, the paragraph element is only rendered when the `show` signal is `true`.\nWhen the component initializes, the paragraph element does not exist, so the `element` variable is not assigned.\nOnce the `show` signal is set to `true`, the paragraph element is rendered, and the `element` variable is assigned to the paragraph element.\n\nYou can see a detailed view of the ref update lifecycle in this [Solid playground example](https://playground.solidjs.com/anonymous/22a1abfa-a0f5-44a6-bbe6-40387cf63b95).\n\n## Forwarding refs\n\nForwarding refs is a technique that allows you to pass a ref from a parent component to a child component.\nThis is useful when you want to access the DOM element of a child component from the parent component.\n\nTo forward a ref, you need to pass the ref to the child component, and then assign the ref to the child component's element.\n\nWhen a child component receives a `ref` attribute from its parent, the `ref` is passed as a callback function.\nThis is regardless of whether the parent passed it as a simple assignment or a callback.\n\nOnce the child component receives the `ref`, it can be assigned to the element that the child component wants to expose through the `ref` attribute.\nTo access the `ref` in the child component, it is passed as a prop:\n\n```tsx\n// Parent component\nimport { Canvas } from \"./Canvas.jsx\"\n\nfunction ParentComponent() {\n\tlet canvasRef\n\n\tconst animateCanvas = () =\u003e {\n\t\t// Manipulate the canvas using canvasRef...\n\t}\n\n\treturn (\n\t\t\u003cdiv\u003e\n\t\t\t\u003cCanvas ref={canvasRef} /\u003e\n\t\t\t\u003cbutton onClick={animateCanvas}\u003eAnimate Canvas\u003c/button\u003e\n\t\t\u003c/div\u003e\n\t)\n}\n\n// Child component\nfunction Canvas(props) {\n\treturn (\n\t\t\u003cdiv className=\"canvas-container\"\u003e\n\t\t\t\u003ccanvas ref={props.ref} /\u003e {/* Assign the ref to the canvas element */}\n\t\t\u003c/div\u003e\n\t)\n}\n```\n\nIn this example, the `canvas` element is directly assigned the `ref` attribute through the `props.ref` variable.\nThis forwards the reference to the parent component, giving it direct access to the `canvas` element.\n\n## Directives\n\nDirectives allow the attachment of reusable behaviours to DOM elements.\nThe [`use:`](/reference/jsx-attributes/use) prefix is used to denote these custom directives.\nUnlike props or attributes, directives operate at a lower level through providing fine-grained control over the elements they are attached to.\n\nDirectives are like callback refs but they enable two extra features:\n\n- Having multiple directives on an element.\n- Passing in reactive data to the callback.\n\nA directive is essentially a function with a specific signature:\n\n```typescript\nfunction directive(element: Element, accessor: () =\u003e any): void\n\n```\n\n- `element`: The DOM element that the directive is applied to.\n- `accessor`: A function that gives access to the value(s) passed to the directive.\n\nThe directive functions are called at render time, but are called before the element is added to the DOM.\nDue to this order, elements are fully primed with their attributes, properties, or event listeners, therefore minimizing unexpected behaviors or premature interactions.\n\nWithin directives, you're able to perform a variety of tasks, including:\n\n- creating [signals](/concepts/signals)\n- initiating [effects](/guides/state-management#reacting-to-changes)\n- adding [event listeners](/concepts/components/event-handlers)\n- and more.\n\nTo learn more about directives and how they work with TypeScript, refer to our [TypeScript for Solid guide](/configuration/typescript).",
|
|
"url": "https://github.com/solidjs/solid-docs/blob/HEAD/src/routes/concepts/refs.mdx",
|
|
"metadata": {
|
|
"path": "src/routes/concepts/refs.mdx",
|
|
"repo": "solidjs/solid-docs",
|
|
"repo_url": "https://github.com/solidjs/solid-docs.git",
|
|
"size": 7336,
|
|
"source_type": "github"
|
|
},
|
|
"hash": "23eb363bdac5daf684ab572a9d2dbcde40d501cedde1665c141e54f4a8d6feab",
|
|
"timestamp": "2026-02-23T11:43:00.1868377+01:00"
|
|
} |