Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6214

Accessing the Wrapper Component's Props in a HOC to return a WrappedComponent with Additional Props

$
0
0

I am writing a higher order component that essentially takes in a wrapped component and uses the wrapped component props to define a set of functions and then add these functions to the props of the returned component.

This is to be done in typescript. The issue is that I do not know how to access the prop 'favourites' of the WrappedComponent and how to define the props for the HOC.

I have written out some code below to illustrate the structure.

   function withImageInfo(WrappedComponent: React.Component) {     return class extends React.Component<??> {       constructor(props: withImageInfoProps) {         super(props)         this.checkFavourited = this.checkFavourited.bind(this)       }       checkFavourited (nasaId: string): boolean {         let favourited: boolean = false         if (this.props.favourites.some(favourite => favourite.nasaId === nasaId)) {           favourited = true         }         return favourited       }       render() {         return <WrappedComponent           checkFavourited={this.checkFavourited}           {...this.props}         />       }

I have been researching and came across this article which described inheritance inversion to access the WrappedComponent's props- here is a snippet from that article in javascript illustrating this:

function iiHOC(WrappedComponent) {  return class Enhancer extends WrappedComponent {    render() {      if (this.props.loggedIn) {        return super.render()      } else {        return null      }    }  }}

The issue is that the render just seems to return the WrappedComponent using super.render() and I cannot find any documentation that describes how to/ if you should return a WrappedComponent with additional props this way.

In my HOC, I could pass in the props I need from the WrappedComponent as separate parameters like so:

function withImageInfo(WrappedComponent: React.Component, favourites: thumbnail[]) {

But I was wondering if I could access these props from the WrappedComponent that is already being passed in.


Viewing all articles
Browse latest Browse all 6214

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>