AppDeveloper
AppDeveloper

Reputation: 2210

Dynamically creating array of components

I've followed this tutorial but the requirement is a bit different. I've a function getArrayList that should generate an array of ItemComponent. The returned component will receive the items prop that is an array.

function getArrayList(ItemComponent) {
    return null // return a new component that renders an array of ItemComponent 
}

class Link extends React.Component {
    render() {
        return <a href={ this.props.item.href }>{ this.props.item.text }</a>;
    }
}

const LinkList = getArrayList(Link);

document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");

if(LinkList) {
    let items = [
        { href:"https://www.yahoo.com", text:"Yahoo" },
        { href:"https://www.bing.com", text:"Bing" }
    ];
    ReactDOM.render(<LinkList items={items} />, rootElement);
    console.log(rootElement.innerHTML);
}

Upvotes: 1

Views: 569

Answers (2)

Dima G
Dima G

Reputation: 2025

You could do something like this:

const LinkList = (items) => (
    <div>
    {items.map(i => (
        <Link key={i.href} item={i}/> // pass the item as props ...
    ))}
    </div>
);

Note: react asks for key property when you dynamically create a list of components.

Upvotes: 0

thedude
thedude

Reputation: 9822

You can do something like this

const getArrayList = (ItemComponent) => {
    const ListComponent = ({items}) => {
        return <div>{items.map(item => <ItemComponent item={item} />)}</div>
    }   
    return ListComponent
}

Upvotes: 2

Related Questions