Home > Software engineering >  Do I wrap the text element correctly?
Do I wrap the text element correctly?

Time:09-21

I have created a wrapper around Text element:

export type PoppinsTextProps = PropsWithChildren<TextProps>

export default function PoppinsText(props: PoppinsTextProps) {

    return React.cloneElement(<Text {...props} />, { style: styles.text }, props.children);

}

const styles = StyleSheet.create({
    text: {
        fontFamily: "Poppins-Medium"
    }

});

It works as expected, for example:

<PoppinsText text20>Hello</PoppinsText>

As you can see, I can pass the same properties on the wrapper as well as on the Text.

The question is would you wrap the Text element in the same way as I do?

CodePudding user response:

No. we don't need to call cloneElement for wrapping a component, we can just return the Text component with the props.

export default function PoppinsText(props: PoppinsTextProps) {
    const {style, ...otherProps} = props
    return <Text {...otherProps} style={StyleSheet.flatten([style, styles.text])} />
}

We would use cloneElement if we want to touch the children or input component props.

For example, have different props provided by different container:

const ReverseContainer = () => {
  const newStyle = { color: "red" };
  const RenderChildren = () =>
    React.Children.map(props.children, (child) => {
      return React.cloneElement(child, {
        style: StyleSheet.flatten([props.childrenStyle, newStyle]),
      });
    });
  return <Card>{<RenderChildren />}</Card>;
};

BTW, maybe you just want to define your preset: https://wix.github.io/react-native-ui-lib/foundation/style

  • Related