Search code examples
javascriptreactjstypescriptreact-typescript

Why does my camelCase attributes work well with TypeScript but show an error in JS in React?


I'm working with my own React component library in coded in TypeScript, which I use with React JS projects. When I use my components in TypeScript they work well with their attributes, but in JS I have errors in the console. Exemple:

TS component:

const Button: React.FC<props> = ({ btnStyle, ...otherProps }) => { ...component }

Types declaration:

interface props {
    btnStyle?: string,
}

Component used in JS or TS:

<Button btnStyle="plain">Button</Button>

And the error I get:

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

How could I use camelCase like in TS in JS?

Thanks!


Solution

  • Okay I found the problem, it's coming from Styled Components, which puts the props on the generated HTML:

    <button btnStyle="style">Button</button>
    

    This is how I fixed it:

    import React from "react"
    
    interface props {
        $btnStyle?: string
    }
    
    const Button: React.FC<props> = ({ btnStyle, children, ...otherProps }) => {
        return (
            <button $btnStyle={btnStyle} {...otherProps}>{children}</button>
        )
    }
    

    Check here for the documentation