In Solid.js, ref is used to obtain a direct reference to DOM elements or component instances. This is particularly useful when you need to directly manipulate the DOM or components, such as focusing an input field, accessing the dimensions or position of an element, or updating the interface without altering the state.
How to Use Ref
To use ref in Solid.js, create a signal using createSignal and pass it as the ref attribute to DOM elements in JSX. When the component renders, Solid.js automatically assigns the element's reference to this signal.
Example Code
Here is a simple example demonstrating how to use ref to focus an input field:
jsximport { createSignal, onMount } from 'solid-js'; function App() { // Create a ref const [inputRef, setInputRef] = createSignal(); // Focus the input field after component mount onMount(() => { inputRef().focus(); }); return ( <div> <input ref={inputRef} /> <button onClick={() => inputRef().focus()}> Focus the input field </button> </div> ); } export default App;
In this example, createSignal creates a signal inputRef that stores a reference to the DOM element. The line ref={inputRef} assigns the input field's reference to inputRef. Within the onMount hook, inputRef() retrieves the reference and invokes its focus method to focus the input. Additionally, a button is included that focuses the input field when clicked.
Use Cases
- Auto-focus: As shown in the example, automatically focus on a specific input field when the page loads.
- Dynamic measurement of element dimensions: In responsive design, you may need to adjust layouts or handle animations based on the element's dimensions.
- Integrating third-party DOM libraries: When integrating with non-reactive third-party libraries, you often need to directly manipulate the DOM.
Using ref provides a way to bypass the conventional data flow, enabling more flexible handling in specific scenarios. However, it is recommended to use it only when necessary to maintain the component's reactivity and declarative nature.