Skip to content

Instantly share code, notes, and snippets.

@sabesansathananthan
Created June 19, 2021 20:55
Show Gist options
  • Save sabesansathananthan/29e57203b9356b56d304692bab7c8c7e to your computer and use it in GitHub Desktop.
Save sabesansathananthan/29e57203b9356b56d304692bab7c8c7e to your computer and use it in GitHub Desktop.
How React Components Are Reused
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// Define the custom prop attribute "forwardedRef" as ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// Note the second parameter "ref" of the React.forwardRef callback.
// We can pass it to LogProps as a regular prop property, such as "forwardedRef"
// Then it can be mounted on the sub-components wrapped by LogProps.
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment