Is there a way in React to separate the props object based on an Typescript interface which extends multiple other interfaces? The other way I see, is to pass duplicate props to components that won't use them which is not the optimal solution.
interface IProps extends IAProps, IBProps {}
const Component1: SFC<IProps> = (props) =>
return (
<Component2
{...props} <--- only IAProps
/>
<Component3
{...props} <--- only IBProps
/>
);
}
You can use the &
to merge interfaces. Such as <ScreenProps extends {} & SliderProps & ReactNavigationProps>
Example:
interface AProps {
testa: any
}
interface BProps {
testb: any
}
class Test extends Component<AProps & BProps> {
// ...
}
// or
<IProps extends AProps & BProps>
class Test extends Component<IProps> {
// ...
}
if you want your component to accept any type of props based on interfaces you can do this:
const Component1: SFC<IAProps & IBProps> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
Note that: if not your all props are required, you can use the optional props in each interface as the following:
interface IAProps {
name: string; // required
age?: number; //optional
}
or if your all interface's pops should be marked as required but you still want to not use all of them in your component you can do this:
const Component1: SFC<Partial<IAProps> & Partial<IBProps>> = (props) =>
return (
<Component2
{...props} <---IAProps
/>
<Component3
{...props} <--- IBProps
/>
);
}
something to mention, that Partial
will mark all your interface's props as optional
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With