Skip to content

Instantly share code, notes, and snippets.

@mrcoles
Created March 6, 2019 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcoles/9405b4ccd870a3493d5ddb89c3047324 to your computer and use it in GitHub Desktop.
Save mrcoles/9405b4ccd870a3493d5ddb89c3047324 to your computer and use it in GitHub Desktop.
A simple function to split up a props object into specified `customProps` that match `keys` and the remaining `spreadProps`
declare module "extract-props" {
export interface ExtractedProps {
spreadProps: object;
customProps: object;
}
export default function extractProps(props: object, keys: string[]): ExtractedProps;
}
const extractProps = (props, keys) => {
const spreadProps = {...props};
const customProps = {};
keys.forEach(k => {
if (k in spreadProps) {
customProps[k] = spreadProps[k];
delete spreadProps[k];
}
});
return { spreadProps, customProps };
};
export default extractProps;
export interface ExtractedProps {
spreadProps: object;
customProps: object;
}
const extractProps = (props: object, keys: string[]): ExtractedProps => {
const spreadProps = { ...props };
const customProps = {};
keys.forEach(k => {
if (k in spreadProps) {
customProps[k] = spreadProps[k];
delete spreadProps[k];
}
});
return { spreadProps, customProps };
};
export default extractProps;
@mrcoles
Copy link
Author

mrcoles commented Mar 6, 2019

The main idea is if you have a React module and want pass through most props into a child component, but want to extract some custom ones to do something different with them. Perhaps you don’t want to pass the custom ones along or you want to avoid warnings such as: “Warning: Received true for a non-boolean attribute warning.”

import classNames from 'classnames';
import React from 'react';

import extractProps from './extract-props';

export default props => {
  const { spreadProps, customProps } = extractProps(props, ['isWarning']);
  const { isWarning } = customProps;
  return <div {...spreadProps} className={classNames(spreadProps.className, { 'warning': isWarning })} />
}

Also, I’m playing around with Typescript. It seems like a potential issue here is that props would be typed, so it’d be better if the function could do something more generic with object types that are passed it…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment