Search code examples
javascriptreactjstypescriptstyled-components

How to disable a styled.button in React styled-components?


I have created the following very basic styled-components styled button:

import styled from 'styled-components';

const StyledButton = styled.button``;

export const Button = () => {
    return <StyledButton>Default label</StyledButton>;
};

Then when creating an instance of one I am trying to disable it:

<Button disabled />

VSCode/React is not allowing this, throwing the following error:

Type '{ disabled: true; }' is not assignable to type 'IntrinsicAttributes'.
    Property 'disabled' does not exist on type 'IntrinsicAttributes'.ts(2322)

HTML buttons have a disabled attribute and the styled-component docs state:

StyledComponent
...
This component can take any prop. It passes it on to the HTML node if it's a
valid attribute, otherwise it only passes it into interpolated functions. 
(see Tagged Template Literal)

Resulting in me being a bit stumped. Does anyone know why this might be, please?

Thank you for reading.


Solution

  • you have to pass the prop to the Component and, as you are using strict react, you have to declare type of props:

    
    import styled from 'styled-components';
    
    const StyledButton = styled.button``;
    
    export const Button = ({disabled=false}: {disabled: boolean}) => {
        return <StyledButton disabled={disabled}>Default label</StyledButton>;
    };