S
SolidJS12mo ago
pronoob

How to define reference for a component?

How can I define ref for a custom component with TypeScript?
14 Replies
Alex Lohr
Alex Lohr12mo ago
Either use createSignal<HTMLElement>() or let ref: HTMLElement and use an exclamation mark in the ref={ref!} property.
pronoob
pronoob12mo 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 Lohr12mo 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
pronoob12mo ago
Can you provide an example?
Alex Lohr
Alex Lohr12mo ago
But what's the use case?
pronoob
pronoob12mo 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 Lohr12mo ago
Why not use an Accessor<string> to update the value using solid's reactive system?
pronoob
pronoob12mo ago
Is that documented?
Alex Lohr
Alex Lohr12mo 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
pronoob12mo ago
setValue is to be passed to the Note component though?
Alex Lohr
Alex Lohr12mo ago
Yes. Or if you want to use a store, you can do that, too.
pronoob
pronoob12mo ago
Also, one last question, what are the differences between stores and signals?
Alex Lohr
Alex Lohr12mo 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
pronoob12mo ago
👍 thanks!
Want results from more Discord servers?
Add your server
More Posts