S
SolidJS•2y ago
Grahf

I don't like refs

Not really a solidJS question but there are smart people here. If there's a rule against this I will remove this post. I am storing a bunch of refs in an array like this: <p ref={(el) => setRefs((p) => [...p, el])} .....> Stuff From Database </p> The resulting array of refs have worked fine for what I've used them for so far. Each <p> element is the result of a value pulled from a database. But what I just implemented is the ability to search the database and get back a subset of the <p> elements. The goal is to be able to click on each item in the subset that's returned from the search and .scrollIntoView the corresponding <p> element in the main page. If I was doing this with ids I would just give each <p> element an id of the primary key from the database. When the user searches each of their search results will also have the primary key from the database and I could just getElementById the element with the id of what the user clicked on and .scrollIntoView to it. That's how I imagine it in my head. Not sure how do to that with a ref. I could check the textContent of each ref in the array of refs and see if it matches the textContent of what the user clicked on and then scrollIntoView that ref?
4 Replies
Otonashi
Otonashi•2y ago
you could use ids, nothing is restricting you to refs really, though i don't think your problem here has to do with refs but with storing them in an array instead of a map or object etc like maybe a store since that's the simplest way to do it (if it even needs to be reactive), then do store[primaryKey].scrollIntoView()
Grahf
GrahfOP•2y ago
Thank you. Not sure if this is what you meant or not but I went with this: setRefs((p) => [...p, { ref: el, item:itemId }]) So yes I use an object now to store the ref and the items Id. Then I use the find function to find the right ref to scroll into view.
const handleClick = (id) => {
const matchingRef = refs().find((ref) => ref.item === id)
matchingRef.ref.scrollIntoView()
}
const handleClick = (id) => {
const matchingRef = refs().find((ref) => ref.item === id)
matchingRef.ref.scrollIntoView()
}
Otonashi
Otonashi•2y ago
setRefs((p) => ({...p, [itemId]: el }))
setRefs((p) => ({...p, [itemId]: el }))
const handleClick = (id) => {
const matchingRef = refs[id];
matchingRef.scrollIntoView()
}
const handleClick = (id) => {
const matchingRef = refs[id];
matchingRef.scrollIntoView()
}
Grahf
GrahfOP•2y ago
oh 😅
Want results from more Discord servers?
Add your server