I am trying to spread some props conditionally but I am getting an error
Type '{ activeStyles: { [key: string]: string; }; onClick: () => void; text: string; } | { inactiveStyles: { [key: string]: string; }; onClick: () => void; text: string; }' is not assignable to type 'IntrinsicAttributes & BtnProps'. Type '{ activeStyles: { [key: string]: string; }; onClick: () => void; text: string; }' is missing the following properties from type 'BtnProps': bg, color
This is my component:
interface BtnProps {
bg: string
text: string
color: string
onClick: () => void
}
export const Toggle: React.FC = (): JSX.Element => {
const [btnClicked, setBtnClicked] = useState(true)
const MyBtn = ({ text, bg, color, onClick }: BtnProps) => {
return <Button {...{ bg, color, onClick, size: 'sm' }}>{text}</Button>
}
const activeStyles: { [key: string]: string } = { color: 'white', bg: 'blue.500' }
const inactiveStyles: { [key: string]: string } = { color: 'blue.500', bg: 'white' }
console.log(activeStyles) // { color: 'white', bg: 'blue.500' }
return (
<Center d="flex">
<MyBtn
{
...{
onClick: () => setBtnClicked(true),
text: 'document',
...(btnClicked ? { ...activeStyles } : { ...inactiveStyles }),
}
}
/>
</Center>
)
}
To get it working I should do this which is the same I think:
<MyBtn
{...{
onClick: () => setBtnClicked(true),
text: 'Document',
...(btnClicked ? { color: 'white', bg: 'blue.500' } : { color: 'blue.500', bg: 'white' }),
}}
/>
Any thoughts?
You have to extend your interface from DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>,HTMLButtonElement>
so it can have properties of default button. the full code is
import React, {
ButtonHTMLAttributes,
DetailedHTMLProps,
FunctionComponent,
HTMLProps,
} from "react";
interface BtnProps extends DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>,HTMLButtonElement> {
bg: string
text: string
color: string
onClick: () => void
}
<MyBtn
onClick={() => setBtnClicked(true)}
text="document"
{...(btnClicked ? activeStyles : inactiveStyles)}
/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.