Home > Back-end >  (MUI Textfield) Uncaught TypeError: Cannot read properties of undefined (reading 'focus')
(MUI Textfield) Uncaught TypeError: Cannot read properties of undefined (reading 'focus')

Time:05-19

I am currently using the useRef hook on the Material Ui Textfield, and I kept getting the error Uncaught TypeError: Cannot read properties of undefined (reading 'focus'), and I have no idea how to solve. My code looks like this:

const LoginTextField = styled(TextField)({
  '& .MuiInput-underline:after': {
    borderBottomColor: 'white',
  },
  '& .MuiOutlinedInput-root': {
    '& fieldset': {
      borderColor: '#263238',
    },
    input: { color: 'white' },
    backgroundColor: '#263238'
  }
});

export default function test() {

  const userRef = useRef();
  const [loginEmail, setLoginEmail] = useState('');

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

<LoginTextField label='Email' variant='outlined' onChange={(e) => setLoginEmail(e.target.value)} 
 inputRef={userRef} InputLabelProps={{ style: { color: 'white' } }} />
}

Anybody has an idea what is wrong with my code? Much thanks.

CodePudding user response:

hey I think it would be better if you first initialise the value on the userRef().

So think of useRef as the useState, where the state is saved on the next render so I think you should decide also what the useRef you want to do, like update the email or password?

For instance: useRef('') or null or whatever you want to be the default/ initial value/ state in your case.

Then maybe you could create a function


const myFunction = () => {
// update the state or what you actually want to implement
}

Then I would run myFunction inside the useEffect.

Hope that kinda helps.

Check also this: https://dmitripavlutin.com/react-useref-guide/

  • Related