・In React, LSP indicates that when you expand the base component or HTML, you should not break base functionality.
Bad code
// You can not use the normal button
const CustomButton = ({ label }: { label: string }) => {
return <button>{label}</button>;
};
// The onClick is ignored if you pass. And type is an error.
<CustomButton label="preserve" onClick={() => alert('Preserved')} />
Good code
You should extend all attributes of the button and pass it.
import { ComponentPropsWithoutRef } from 'react';
//Define the type to receive all of the attributes
interface ButtonProps extends ComponentPropsWithoutRef<'button'> {
variant?: 'primary' | 'secondary';
}
const CustomButton = ({ variant, children, ...rest }: ButtonProps) => {
const style = variant === 'primary' ? { backgroundColor: 'blue' } : {};
// pass all of the attributes such as onClick or type by `...rest`
return (
<button style={style} {...rest}>
{children}
</button>
);
};
<CustomButton variant="primary" onClick={() => console.log('Submit')}>
Submit
</CustomButton>
In this way, the essence of LSP is to ensure that “whatever the parent (standard element) can do, the child (custom component) can do as well.”
Top comments (0)