Created
March 6, 2019 16:13
-
-
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`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
declare module "extract-props" { | |
export interface ExtractedProps { | |
spreadProps: object; | |
customProps: object; | |
} | |
export default function extractProps(props: object, keys: string[]): ExtractedProps; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 attributewarning
.”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…