Sometimes I have a styled component like:
import styled from 'styled-components';
const StyledButton = styled.button;
And then I need to use it like this
export default function CloseButton() {
return <StyledButton>Close</StyledButton>
}
And use it like <CloseButton />
.
But what if I need to use it like <CloseButton onClick={doSomething} />
?
I would have to change my CloseButton
component to:
type Props = {
onClick: () => void;
}
export default function CloseButton(props: Props) {
return <StyledButton onClick={props.onClick}>Close</StyledButton>
}
This sucks. So a better way would be just to pass all the props like:
export default function CloseButton(props: any) {
return <StyledButton {...props}>Close</StyledButton>
}
Thats clean and simple... but how to avoid any
type of props
and tell typescript to use props from StyledButton?
It seems that this:
export default function CloseButton(props: typeof StyledButton.defaultProps) {
return <StyledButton {...props}>Close</StyledButton>
}
is working almost perfect. It does show HTML attributes of a <button>
element, although it does not show StyledComponents props like as and forwardAs