Reputation: 266
I'm just getting started with React and ES6 and I am trying to DRY up my app a bit. What I'm looking to do is create a component that takes a collection and an attribute of the items in that collection and turn it into a list. For example, if I pass in a group of authors and specify last name, it will create a list of the authors' last names; using the same component I would like to use it elsewhere and pass in a group of songs and list them out by title.
Here's what I have so far:
ItemList:
import PropTypes from 'prop-types'
import React from 'react'
import Item from './Item'
export default class ItemList extends React.Component {
constructor(props){
super(props)
}
render() {
let items
if(this.props.items.length === 0){
items = <div>Nothing Found</div>
} else {
items = this.props.items.map(item => {
return(
<Item item={item} displayAttribute={this.props.displayAttribute}
)
});
}
return (
<div className="item-index">
<div className="list-group">{items}</div>
</div>
);
}
}
Item:
import PropTypes from 'prop-types'
import React from 'react'
export default class Item extends React.Component {
constructor(props){
super(props)
}
render() {
return (
<div className="list-group-item" data-index={this.props.item.id}>
<div className="item-attribute">
*This is where I want to print the item's display attribute*
</div>
</div>
);
}
}
Elsewhere in the app, I would like to be able to call something like the following:
<ItemList items={this.state.authors} displayAttribute="last_name" />
or
<ItemList items={this.state.songs} displayAttribute="title" />
and the component would create a list using the specified attribute
Upvotes: 0
Views: 673
Reputation: 8375
If I understood you correctly this should do (in your item list):
<div className="item-attribute">
{this.props.item[this.props.displayAttribute]}
</div>
Upvotes: 2