Search code examples
javascriptreactjsantdstyled-components

React does not recognize the `backgroundColor` prop on a DOM element


I've been searching about this error a while but couldn't find a solution... I'm using styled components and ant.design.

Button Component

import React from 'react'
import {Btn} from './style';

const ComponentButton = (props) =>{

  const  {title, backgroundColor,color, hoverColor, handleClick,shape} = props

 return(
      <Btn 
        shape={shape || "round"} 
        onClick={handleClick}
        backgroundColor={backgroundColor}
        color={color}
        hoverColor={hoverColor}
      >
         {title}   
      </Btn>
  )
}

export default ComponentButton;

styled-Component

import styled, {css} from 'styled-components';
import {primaryColor, white} from '../../../../config';
import { Button } from 'antd';



export const Btn = styled(Button)`
   ${(props, {color, backgroundColor, hoverColor, width} = props) =>
      css`
        color: ${color ? color : white};
        background-color: ${backgroundColor ? backgroundColor : primaryColor} !important; 
        width: ${`${width}px` ? `${width}px` : '-webkit-fill-available'};
        border: none !important;

        &:hover, &:focus{
          color: ${hoverColor ? hoverColor : white};
          border: none !important;
        }
        &:after{
          box-shadow: none !important;
        }

    `} 
` 

I don't know why I still getting this error:

React does not recognize the backgroundColor prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase backgroundcolor instead.


Solution

  • styled-components will automatically add all props into DOM element by default, such as:

      <button backgroundColor="" color="" hoverColor="" ... />
    

    and react will check the props of the DOM element are legal.

    also, this line ${(props, {color, backgroundColor, hoverColor, width} = props) looks a little weird, this should only have one parameter.

    you can try this:

    // avoid pass all props into button element
    export const Btn = styled(({color, backgroundColor, hoverColor, width, ...props}) => <Button {...props} />)`
       ${(p = props) =>
          css`
            color: ${p.color ? p.color : white};
            background-color: ${p.backgroundColor ? p.backgroundColor : primaryColor} !important; 
            width: ${`${p.width}px` ? `${p.width}px` : '-webkit-fill-available'};
            border: none !important;
    
            &:hover, &:focus{
              color: ${p.hoverColor ? p.hoverColor : white};
              border: none !important;
            }
            &:after{
              box-shadow: none !important;
            }
    
        `} 
    `