0

I am building a custom dropdown with hooks and I ran into this issue in which the ref.current for the li elements rendered from an array is undefined. However, my other ref isn't. I'm sure I am doing something wrong, I just can't seem to pin point if it's losing or failing to bind the .current property.

I'm using styled-components, thus the naming convention.

How come input succesfully references the correct jsx element, but link is undefined?

I am exploring strategy to use keyboard navigation entirely with hooks, so if there are any suggestion, glad to hear them :D

const CustomDropdown({ handleCategoryClick, width }) => {
    const input = useRef();
    const link = useRef();

    useEffect(() => {
        input.current.focus();
    }, []);

    const toggleList = () => {
        if (isOpen) {
            setIsOpen(false);
            return;
        }
        setIsOpen(true);
        setOptions(dropdownOptions);
    };
return (
    return (
        <DDWrapper>
            <DropdownContainer>
                <InputContainer onClick={toggleList}>
                    <DropdownInput
                        ref={input}
                        name="customDropdown"
                        width={width}
                        isOpen={isOpen}
                        defaultValue={inputValue}
                        placeholder="Select a filter"
                    />
                </InputContainer>
            </DropdownContainer>
            {isOpen && (
                <DDList width={251} isOpen={isOpen} onClick={handleCategoryClick} role="navigation">
                    {options.map(({ label }, i) => (
                        <DDItem
                            id="item"
                            onKeyDown={handleKeyDown}
                            onClick={hideList}
                            data-value={label}
                            key={i}
                            width={width}
                            ref={link}
                        >
                            {label}
                        </DDItem>
                    ))}
                </DDList>
            )}
        </DDWrapper>
    );
13
  • useRef() should not be used in a loop Commented Mar 14, 2019 at 20:49
  • @BrianLe got it! Thanks, any alternative methods to achieve the desired results, you can suggest? Commented Mar 14, 2019 at 20:50
  • 1
    You can create an array of refs like in this question: stackoverflow.com/questions/54940399/… Commented Mar 14, 2019 at 20:53
  • 1
    If it doesn't help, I will dive into it a bit further. Posting an answer with just a link is tedious Commented Mar 14, 2019 at 20:55
  • 1
    Hmm, weird. I think you should open another question and add a sandbox with it Commented Mar 14, 2019 at 21:58

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.