How to define reference for a component?

How can I define ref for a custom component with TypeScript?
14 Replies
Alex Lohr
Alex Lohr2y ago
Either use createSignal<HTMLElement>() or let ref: HTMLElement and use an exclamation mark in the ref={ref!} property.
pronoob
pronoobOP2y ago
How do I forward the ref to a custom component?
type Props = { ref: ??? };

const Note: Component<Props> = (props) => {
return (
<button>Hello, World!</button>
);
};
type Props = { ref: ??? };

const Note: Component<Props> = (props) => {
return (
<button>Hello, World!</button>
);
};
Alex Lohr
Alex Lohr2y ago
refs are usually only for intrinsic elements. Otherwise, all you get is a prop to define yourself, so you'd type that as Setter<HTMLElement>.
pronoob
pronoobOP2y ago
Can you provide an example?
Alex Lohr
Alex Lohr2y ago
But what's the use case?
pronoob
pronoobOP2y ago
I have a textarea element, I am creating a reference to it and passing it to a custom component to set the value of it dynamically
<For each={notes}>{(note) => <Note ref={textarea!} ... />}</For>
<textarea
ref={textarea}
></textarea>
<For each={notes}>{(note) => <Note ref={textarea!} ... />}</For>
<textarea
ref={textarea}
></textarea>
Alex Lohr
Alex Lohr2y ago
Why not use an Accessor<string> to update the value using solid's reactive system?
pronoob
pronoobOP2y ago
Is that documented?
Alex Lohr
Alex Lohr2y ago
<textarea value={value()} /> should do the trick. Just use setValue() to overwrite the current value. It will only be overwritten if setValue is called, so the reactive updates won't clash with user input.
pronoob
pronoobOP2y ago
setValue is to be passed to the Note component though?
Alex Lohr
Alex Lohr2y ago
Yes. Or if you want to use a store, you can do that, too.
pronoob
pronoobOP2y ago
Also, one last question, what are the differences between stores and signals?
Alex Lohr
Alex Lohr2y ago
Signals are there for simple value literals. They are used by stores under the hood, which are for objects and arrays. So if you have deep data, use a store, and put flat data into signals.
pronoob
pronoobOP2y ago
👍 thanks!
Want results from more Discord servers?
Add your server