Read input from many child components

I have a page with hundreds of text fields. From the page, I'm trying to read the user's input from each field when they click on a button. useState can work but would be too slow What would be a better solution? Should/how do I use useRef in this case?
11 Replies
Brendonovich
Brendonovich2y ago
Sounds like you’re creating a form, have you looked into something like react-hook-form?
Mocha
Mocha2y ago
It seems to almost work, thanks! But it's very slow too. All I need is to read the values as-is.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Mocha
Mocha2y ago
It's not really a form, but rather a list of MUI cards that each have TextField. Is it possible to use HTML forms with such custom components?
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Mocha
Mocha2y ago
That didn't work with my current setup (too many independent components). Using a React state is the closest I got to, but it's a performance killer
Brendonovich
Brendonovich2y ago
Not sure what you're doing if react-hook-form can't handle all your componets, useState is way less efficient than handling state on submit
Mocha
Mocha2y ago
I don't want to do anything with the user's input until onSubmit. react-hook-form seemed slow. localStorage is the most efficient option I got so far. onChange={val => localStorage.setItem(key, val)} Then arr.map(el => ({...el, val: localStorage.get(key)})) Also react-hook-form seems to target forms with a fixed amount of fields. What I have is hundreds of dynamically generated fields, each in a separate child component
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Brendonovich
Brendonovich2y ago
That's exactly what react-hook-form does, it leaves components as uncontrolled until u hit submit Dynamic forms are possible in rhf but they require a bit more effort, i'll give u that
Mocha
Mocha2y ago
Yes, so I'm trying to avoid that effort and complexity : ) but it's good library for sure I tried the following: const textFields = useRef<HTMLInputElement[]>([]) Then for each component, I used forwardRef<HTMLInputElement, Props>(props, ref) and passed ref to the TextField Then from the parent: ref={el => { if (el) textFields.current[idx] = el }} It didn't work this way, and I'm not sure why textFields.current.map(t => t.value) returns [undefined, undefined, ...] Update: textFields.current is of type HTMLDivElement[] and contains a lot of the HTML that goes behind MUI's TextField component, so this works 🙂 I will keep trying to get to the value field and post the answer here Solution:
textFields.current.map(div => div.querySelector('input')?.value)
textFields.current.map(div => div.querySelector('input')?.value)
For MUI's Autocomplete:
div.innerText.split('\n')
div.innerText.split('\n')
Thanks everyone for your help!
Want results from more Discord servers?
Add your server