Use multiple interfaces/types as Props in react with typescript.
Umesh Verma
Posted on January 15, 2021
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.
Posted on January 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 8, 2023