Declare same props as an underlying component, without copying them over

reasonreact

#1

I’m evaluating whether ReasonML is a good fit for my React Native project, and I got stuck when trying to create a more-specific component that uses a base component, but changes its props slightly. For example, this is my AppTextInput that renders the React Native TextInput and has exactly the same props, but taps into it’s style prop in order to respect the current theme:

const AppTextInput = props => {
  const theme = useTheme();
  return (
    <TextInput
      {...props}
      style={[
        {
          color: theme.textColors.primary
        }, // default theme styles are provided
        props.style // given style is respected, and can override the above
      ]}
    />
  );
};

I could of course re-declare the numerous TextInput's props (https://github.com/reason-react-native/react-native/blob/master/src/components/TextInput.re), but this way I would need to change AppTextInput anytime the original component updates. I use this pattern quite a lot to create different flavors of components.

Is there a way to do this more elegantly in ReasonML? I’ve explored currying and using TextInput.makeProps, but I need to access my hook in order to get current theme color, which I’ll merge with the given style.

Thanks!


#2

Hey @vknez, I think it’s a bit of a hard case for OCaml’s type system here, as it’s not easy to express: “this new function takes all the same args as this other function” without listing them. I’d recommend just copy pasting TextInput.makeProps args, since it’s unlikely to change very frequently anyway and if it did you’d probably want to check your wrapper function anyway.


#3

Here’s some more info on this https://reasonml.github.io/reason-react/docs/en/props-spread


#4

Thanks, @bsansouci. I’ll need to get accustomed to that :slight_smile:

I had a go with reusing TextInput.makeProps and then providing my own AppTextInput.make, which taps into style, and then creates TextInput.make element, but this is 1/ valid only when props are exactly the same, and 2/ non-safe, as React.createElement(...make..., ...props...) allows unknown props to be passed. So I guess it is not worth it.


#5

Thanks @yawaramin. However, I read the docs and understood that there’s no props spread in ReasonML.