5
votes

I want to render table cell dynamically. Each cell is a React component. I'm trying to export these React components as a wrap function.

For example:

import cellA from './cellA'
import cellB from './cellB'
import cellC from './cellC'

let content = { cellA, cellB, cellC }

function tableize (a) {
    let resultFn = {}
    Object.keys(a).forEach((k) => {
        let element = a[k]
        resultFn[k] = function (data) {
            return (<element data={data} />)
        }
    })
    return resultFn
}

export default tableize(content)

The problem is on this line:

return (<element data={data} />)

The result is browser render list of React components named element, not cellA, cellB, cellC. The function return element as jsx (in < /> tag) because I need to pass props to these React component. But I'm wrong.

How to pass props to this React component that wrapped in a variable?

Thank you!

2
Where is the data props come from? You didn't put data as parameter in function tableize(a) Is it working if you just use <element /> ? - Hana Alaydrus

2 Answers

5
votes

Try this:

function tableize (a) {
    let resultFn = {}
    Object.keys(a).forEach((k) => {
        // Uppercase "E" from Element
        let Element = a[k]
        resultFn[k] = function (data) {
            // Uppercase "E" from Element
            return (<Element data={data} />)
        }
    })
    return resultFn
}
-1
votes

It seem like what you want is a higher order component (HOC)

function wrapper(WrappedComponent) {
  return class extends React.Component {
    render() {
      // Wraps the input component in a container, without mutating it. Good!
      return <WrappedComponent {...this.props} />;
    }
  }
}

Please read this https://facebook.github.io/react/docs/higher-order-components.html