Warning: React does not recognize the X prop on a DOM element

Viewed 16826

I am getting this error when I am just trying to pass props around. Very basic stuff.

interface Props extends Omit<React.HTMLAttributes<HTMLElement>, 'color'>, ChakraProps {
  handleMoveAll: () => void
}

export const MyWrapper: FC<Props> = (props): JSX.Element => (
  <div {...props}>
    <IconBox label="Move All" onClick={props.handleMoveAll}>
      <MyIcon />
    </IconBox>
  </div>
)

And then I call the component MyWrapper on its parent where the warning is coming from.

export const ParentComp: FC<{}> = (): JSX.Element => {
  const myFunction = () => console.log('Hit it')

  return (
      <MyWrapper handleMoveAll={() => myFunction()}>
         <p>Child Component</p>
      </MyWrapper>
  )
}

Warning: React does not recognize the handleMoveAll prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase handlemoveall instead. If you accidentally passed it from a parent component, remove it from the DOM element.

If I remove this handleMoveAll={() => myFunction()} the warning is gone.

Any ideas?

2 Answers

The problem is <div {...props}> in MyWrapper; that adds the handleMoveAll prop onto the div. What you could do is something like:

export const MyWrapper: FC<Props> = (props): JSX.Element => (
  const {handleMoveAll, ...rest} = props;
  <div {...rest}>
    <IconBox label="Move All" onClick={handleMoveAll}>
      <MyIcon />
    </IconBox>
  </div>
)

to pull out handleMoveAll from the passed-in props, while still passing any other props into the div.

<div {...props} - this is why you are getting a warning.

handleMoveAll is not a valid attribute for a div element. React generates this warning for multiple reasons and one of them is when you try to add a non-standard DOM attribute on a native DOM element.

From React Docs - Unknown Prop Warning:

The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.

Solution

To fix this warning, don't add handleMoveAll attribute on the div element.

const MyWrapper: FC<Props> = ({ handleMoveAll, ...restProps }): JSX.Element => (
  <div {...restProps}>
    <IconBox label="Move All" onClick={handleMoveAll}>
      ...
    ...
  ...
)
Related