I have a lazy load component where I have 3 parameters:
- children: is a component to pass to the
Suspense
component. - height: is the
height
for theLazyLoad
component load icon. - width: is the
width
for theLazyLoad
component load icon.
The LazyLoad
component is the following:
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadCompProps {
children : React.ReactNode;
height ?: string;
width ?: string;
}
const defaultProps: LazyLoadCompProps = {
children,
height: "300px",
width: "300px"
}
const LazyLoad = (props: LazyLoadCompProps) => {
const {children, height, width} = props;
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
LazyLoad.defaultProps = defaultProps;
export default LazyLoad;
But when I start the app with npm start
throw the following error:
TypeScript error in [project]/src/features/GenericComponents/LazyLoad/LazyLoad.tsx(5,21):
Binding element 'children' implicitly has an 'any' type. TS7031
3 | import Loading from "../Loading/Loading";
4 |
> 5 | const LazyLoad = ({ children, height = "300px", width = "300px" }) => {
| ^
6 | return (
7 | <Suspense fallback={<Loading height={height} width={width} />}>
8 | {children}
But I want the parameter children
to be required but without optional value, how can I do this?
CodePudding user response:
best way would be to use the React.FC
type. This will inject the children
variable. You can also set the default variables inside the function parameters.
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadCompProps {
height?: string;
width?: string;
}
const LazyLoad: React.FC<LazyLoadCompProps> = ({children, height = "300px", width = "300px"}) => {
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
export default LazyLoad;
CodePudding user response:
To solve this I add the required and optional parameters in 2 different interfaces and then extends to another interface the optional and required like this:
import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";
interface LazyLoadRequiredProps {
children : React.ReactNode;
}
interface LazyLoadOptionalProps {
height ?: string;
width ?: string;
}
interface LazyLoadProps extends LazyLoadRequiredProps, LazyLoadOptionalProps {}
const defaultProps: LazyLoadOptionalProps = {
height: "300px",
width: "300px",
}
const LazyLoad = (props: LazyLoadProps) => {
const {children, height, width} = props;
return (
<Suspense fallback={<Loading height={height} width={width} />}>
{children}
</Suspense>
);
};
LazyLoad.defaultProps = defaultProps;
export default LazyLoad;
I see this example from the following source: https://dev.to/fullstackchris/react-with-typescript-optional-props-with-default-values-33nc