Reputation: 8938
Getting an error on a parent component with the message of:
Type '{ bar: string; py: string; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'py' does not exist on type 'IntrinsicAttributes & Props'.ts(2322)
parent component:
// striped code
export default async function parent() {
const data = await apiLogic()
return (
<Flex>
<Child bar={data?.bar} py="6" />
</Flex>
)
}
child component:
interface Props {
bar: string
props: any
}
export default function Child({ bar, ...props }: Props) {
return (
<Box {...props}>
// code stripped
</Box>
)
}
Research:
Is there a special way when spreading props
with TypeScript I should be implementing here? How can I resolve the error for Chakra UI StyledProps py
?
Upvotes: 1
Views: 829
Reputation: 619
Chakra UI exports prop types for each component, so your own custom interfaces can be extended with Chakra UI's props, including py
. Since the component is destructuring out the custom props before spreading it into the Box, this should fix the Typescript warning.
Example for Box
:
import { Box, type BoxProps, Flex, Text } from '@chakra-ui/react'
// Extend the exported prop interface for the Chakra UI component
interface CustomProps extends BoxProps {
bar: string;
}
// Use the custom interface that extends Box props and destructure out your custom prop additions
export const Child = ({ bar, ...chakraProps }: CustomProps) => {
// Pass the rest of the Chakra component props to Box
return (
<Box {...chakraProps}>
<Text>{bar}</Text>
</Box>
)
}
export const Parent = () => {
const data = { bar: 'foo' }
return (
<Flex>
<Child bar={data.bar} py="6" />
</Flex>
)
}
export const App = () => {
return <Parent />
}
Note: Written when Chakra UI was version 2.8.2
Upvotes: 0