While developing the react component, with respect to class and functional component. The main concern while developing is to pass props inside so that it will be ready to use in projects.
React functional component
const CustomComponent = () => {
return(<>.....</>);
}
π€ How to pass my props inside the component?
π‘ Let me create an interface for this component that will accept n number of props inside. so that it can be more customize.
Custom Props interface
interface ICustomComponentProps {
height: number;
width: number;
}
Now using these props into the component.
const CustomComponent = (props: ICustomComponentProps) => {
///Decompose props
const { width, height } = props;
/// Handle props
return(<>.....</>);
}
Now props are accessible in the component.
Now I need to create more components.
const CustomComponentB = () => {
return(<>.....</>);
}
Let me pass the same props inside CustomComponentB
.
const CustomComponentB = (props: ICustomComponentProps) => {
///Decompose props
const { width, height } = props;
/// Handle props
return(<>.....</>);
}
Suddenly I realized that I need to add one more property to the above CustomComponentB.
π€ How can I add one more property?
π‘ let me add in the current interface.
interface ICustomComponentProps {
....
fontSize: number;
}
Now the new snippet will be like
const CustomComponentB = (props: ICustomComponentProps) => {
///Decompose props
const { width, height, fontSize } = props;
/// Handle props
return(<>.....</>);
}
Cool it's working, but suddenly CustomComponentA is failing.π
π€ How to fix it?
Let me create another interface that will extend the
ICustomComponentProps
interface INewComponentPropsB extends ICustomComponentProps {
fontSize: number;
}
Now the new snippet will be like
const CustomComponentB = (props: INewComponentPropsB) => {
///Decompose props
const { width, height, fontSize } = props;
/// Handle props
return(<>.....</>);
}
Here ComponentB is using INewComponent props that extend the initial props interface.
Cool it's working,
π€ How to fix it without using extends
keyword?
π‘ use the &
Let me modify interface
interface INewComponentPropsB {
fontSize: number;
}
Now the new snippet will be like
const CustomComponentB = (props: (ICustomComponentProps
& INewComponentPropsB)) => {
///Decompose props
const { width, height, fontSize } = props;
/// Handle props
return(<>.....</>);
}
π It's working !!!
Many Thanks for Reading this content.
Bonus: You can use type
definitions also instead of interface
declartion.
Top comments (4)
Something I've been wondering (and will try shortly) , if I had a function that took a ICustomComponentProps as an argument, could I pass an instance of CustomComponentB (if using the extends method) to it and (if wanted) cast it to a INewComponentPropsB ?
thanks this works for me
Nice. I need it now
Thank you very much for yout solution of combining the interface with &