🔮 react-overrides
Pass props to internal elements of React component by passing overrides
prop.
const PrimaryButton = <CommonButton ...props overrides= Container: props: className: "primary_button__container" // pass className to Container element of CommonButton "aria-role": "button" // pass ARIA attribute Text: component: BigText // replace element component to BigText />;
Where CommonButton
was made with react-overrides
:
; const CommonButton = <Container ...o onClick=propsonClick> <Text ...o>propschildren</Text> </Container>;
Try at CodeSandbox:
Why
There is a need for pass props to elements, or replace his component. Here's some examples:
- You create UI library, and want to provide customization abilities for components. Base UI library used this approach.
- You need unified way to pass any props (for example, ARIA attributes) to common component elements.
Installation
Install core package and babel plugin with yarn:
yarn add react-overrides
yarn add babel-plugin-react-overrides --dev
Or with npm:
npm i react-overrides --save
npm i babel-plugin-react-overrides --save-dev
Further, add react-overrides
to your .babelrc
configuration:
Usage
Create extendable component by passing the default export
from react-overrides
package to the component to be extended.
Example:
;;; const Select = { const opened setOpened = ; return <Container ...o onClick= > <Value ...o>propscurrentValue</Value> opened && <OptionsContainer ...o> propsvalues </OptionsContainer> </Container>};
Extend with component through passing props of internal component:
; const BigOptionSelect = { return <Select ...props overrides= Option: props: className: "big-option-select__option" "aria-role": "button" />}
Replace internal components
You can replace the internal component with a custom one:
;; const FancyGridSelect = { return <Select ...props overrides= OptionsContainer: component: FancyGrid />}
Access to individual props
;;;; const Button = { const Container = <button ...props) />; const Text = <span ...props) />; return <Container ...o className= onClick=propsonClick> <Text className= /> propschildren </Text> </Input> ;;
Flow support
You can use ExtractOverrides
type props helper for infer overrides prop type from components types.
// @flow;; const Option = { return <div>propsb + 2 * propsa</div>;}; const Container = { return <div>propschildren</div>;}; const OverridableProps = Option Container;type TOverridesProps = ExtractOverridesProps<typeof OverridableProps>; const Select = { return <Container ...o> /* For access to individual prop used o().<prop>, o.<prop> throw Flow error */ <Option ...o a=1 b=b || "x" /> </Container> ;}; const OverridedSelect = { return <Select overrides= Option: props: a: 1 /> ;}; // throw flow error:const OverridedSelectWrong = { return <Select overrides= Option: props: a: 3 /> ;};
Acknowledgements
This library inspired by article Better Reusable React Components with the Overrides Pattern.