nez1998
nez1998

Reputation: 15

Using props of a passed component

I am creating an abstract grid and my main component is a and the table have the 3 components (like a normal table) and and I have an option to choose if I want to use the default TableBody, TableHeader or TableFooter or to pass in my own e.g. .

The question is how can I pass the tablebody2 to and use the data like the default TableBody components.

Here is how I define what component to use (if null use default):

let templates = {
  header: null,
  body: <TableBody2 data={this.state.data}/>,
  footer: null

And here is how I'am passing the component to table:

<Table options={this.state.options} data={this.state.data} templates={templates}/>

And I'm not quite getting how I'am I suppose to access the data props of inside

Resolved: In my Table component I call my component(TableBody2) like this (this.props.templates.body(this.props)) and pass it the props of Table so I can access data like this

    function TableBody2(props){
  const tableData = props.data.map((data) => {
    return (
    <td key={data.userId}>{data.userId}</td>
  )
  });
  return (    
    <tbody>
    <tr>
    {tableData}
  </tr>
  </tbody>

  )
} 

Upvotes: 0

Views: 100

Answers (3)

dubes
dubes

Reputation: 5524

It looks like Render-Props pattern is your friend here. The crux of render-props pattern is: You pass a function as a property to your component, and then you can use that function in your render()

From Official Docs:

a render prop is a function prop that a component uses to know what to render.

You can then enhance your Table component to provide more fine grained control over what is rendered. For e.x. You can define your Table component to accept 3 renderProps, let us call them header, body, footer

Your render method of Table can look like:

render() {
    {/* your main table code */}
    {this.prop.header && this.prop.header(this.prop.data)}
    {this.prop.body && this.prop.body(this.prop.data)}
    {this.prop.footer && this.prop.footer(this.prop.data)}
}

Sample usage could be:

<Table data={someData} 
       body={(data) => (<TableBody2 data={data} />)} />

You can take a look at Downshift library code, it uses render props amazingly to provide flexibility.

Upvotes: 2

ionizer
ionizer

Reputation: 1721

In your receiving component you just need to access the data by using, for example, this.props.data or this.props.template. Or, you can try using componentWillReceiveProps() like this:

componentWillReceiveProps(nextProps) {
    console.log(nextProps);
}

Or in constructor(props) the same way as above if it's only a one-time operation.

Upvotes: 0

meta4
meta4

Reputation: 736

I must be sincere that the question is not very clear to me, but if you asking how you access props inside component (Table) then it is: this.props.templates

Upvotes: 0

Related Questions