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

Viewed 9295

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.

2 Answers

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>;
};

You will need to allow props to be examined in the styled component. Like so

import styled, { css } from "styled-components";

const buttonStyles = css`
  display: true
`;

const invertedButtonStyles = css`
  display: true
`;

const getButtonStyles = (props) => {
   
    return props.inverted ? buttonStyles : invertedButtonStyles;
  };


export const CustomButtonContainer = styled.button`
  ${getButtonStyles}
`;
Related