1

I have used useRef hook from react

const myInput = useRef()

And pass it to material-ui OutlinedInput component

<OutlinedInput
  id="outlined-adornment-amount"                                      
  inputRef={myInput}
  type="file"                                            
  startAdornment={<InputAdornment position="start">
                   <FolderIcon fill="#333" />
                    </InputAdornment>}
                      labelWidth={60}
    />

when I try to set the input's property in within useEffect

  useEffect(() => {
        myInput.current.directory = true
    }, [])

I get

Uncaught TypeError: Cannot set property 'directory' of undefined

3
  • Yeah, this can happen because your useEffect came in before the component, you can try to add myInput?.current.directory = true or myInput && myInput.current.directory = true Commented Jan 15, 2021 at 9:01
  • Try this if (myInput.current) { myInput.current.directory = true } Commented Jan 15, 2021 at 9:29
  • @Fried noodles I'm getting error 'incorrect left-hand side in assignment expression' Commented Jan 15, 2021 at 9:48

3 Answers 3

1

I can't see any problem with your code. I tested and everything works fine. Check out this:

https://codesandbox.io/s/hardcore-kare-u5rgm

Sign up to request clarification or add additional context in comments.

2 Comments

The attribute isn't setting tho. It still behaves as a file selector than a folder selector. I have even tried myInput.current.setAttribute('webkitdirectory', ''); still not working
sandbox expired
0

I had exactly the same issue. In my project there were several MUI components and the input was on a modal. In my case what worked was to use a timeout. Not sure if it's the best solution, but it works:

  const myInputRef = useRef();
....
  useEffect(() => {
    setTimeout(() => {
      myInputRef.current.focus();
    }, 0);
  }, []);

Comments

0

maybe it's because the input you used is not actually the input. I think if you log your ref you would have 2 children.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.