Home > Software engineering >  How do I “inherit” core component props in custom created components
How do I “inherit” core component props in custom created components

Time:03-18

I have created a custom component that I want to reuse multiple times throughout my app. The component is itself using a TouchableHighlight inside it.

I want the usage of the component to be able to pass through TouchableHighlight props without having to declare them separately inside the custom component.

A very simple example:

Component:

const CustomComponent = () => (
<TouchableHighlight>
<Text>Custom component</Text>
</TouchableHighlight>)

Usage:

<CustomComponent activeOpacity={0.5} underlayColor=“red” onPress={someAction} />

So to summarise, I’d like the TouchableHighlight to use activeOpacity, underlayColor, and onPress without having to single them out inside the component individually.

Hope that makes sense and I’ve explained it sufficiently.

CodePudding user response:

You can spread the props if you just want it to pass through.

const CustomComponent = (props) => (
<TouchableHighlight ...props>
<Text>Custom component</Text>
</TouchableHighlight>)

CodePudding user response:

Try this:

const CustomComponent = ({touchableHighlightProps, ...otherProps}) => {
  return (
  <TouchableHighlight {...touchableHighlightProps}>
  <Text>Custom component</Text>
  </TouchableHighlight>
  )
}

Then the usage will be:

<CustomComponent touchableHighlightProps={touchableHighlightProps} />
  • Related