VM366:1 Warning: input: `ref` is not a prop. Trying to access it will result in `undefined` being returned

33 Views Asked by At

I try to use React and got the warnging message when only click the button in the first time. And I ask chatGPT, it said all my codes are as expected. Should not have this warnings.

// App.js
import MyRef from "./MyRef";

export default function App() {
  return (
    <>
      <MyRef />
    </>
  );
}

// MyRef.js
import React, {useRef} from 'react'

const MyRef = () => {
  const inputRef = useRef()
  const handleClick = () => {
    console.log(inputRef.current)
  }
  return (
    <div key="hello">
      <input type="text" ref={inputRef}/>
      <button onClick={handleClick}>Click me</button>
    </div>
  )
}

export default MyRef

Warnging messages in the console of Chrome dev tools: Warning: div: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop.

and

Warning: input: ref is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop.

Again, this only happened in the first time to click the button. and when I change: console.log(inputRef.current) to console.log(inputRef.current.value) The warning message disappear when I click the button in the first time.

How can I avoid the warning message if I need to use console.log(inputRef.current)?

1

There are 1 best solutions below

1
likewoahlala On

Hmm I think the warnings are coming from this part of the code key="Hello". You might not need to use key as a prop here. Try removing it and see if it still gives you a warning