javascriptreactjshigh-order-component

Is it possible to pass a string array as parameter using HOC?


I'm using some HOC components in my nextJS application to set some prop values via getInitialProps. But I need to use dynamic values for these props.

In my index component I'm calling withServerProps. Is it possible to pass some string array to it?

index.js

import React, { Component } from 'react'
import { withTranslation } from 'i18n'
import withServerProps from 'with-server-props'

class Index extends Component {
  render () {
    return (<div>Some content</div>)
  }
}

export default withServerProps( // <-- How to pass an array with strings?
  withTranslation()(Index) 
)

I need to get the string array in this function:

with-server-props.js

import React, { Component } from 'react'

export default WrappedComponent =>
  class extends Component {
    static async getInitialProps (context) {
      const { query } = context
      return {
        id: query && query.id
        target: PASSED_ARRAY // <-- Need to recieve the array here
      }
    }
    render () {
      return <WrappedComponent {...this.props} />
    }
  }

Solution

  • Yes you definitely can. Just add some arguments during the export in index.js.

    export default withServerProps(withTranslation()(Index), ["hello"])
    

    Then in your HOC:

    export default function handleServerProps(WrappedComponent, arr) {
      class Hoc extends Component {
        static async getInitialProps (context) {
          const { query } = context
          return {
            id: query && query.id,
            target: arr,
          }
        }
        render () {
          return <WrappedComponent {...this.props} />
        }
      }
    
      return Hoc;
    }