1

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);
}
3
  • 1
    what is your question? Commented Jul 26, 2020 at 9:00
  • how to implement getArrayList that returns an array of components that will receive items (links) as an array and populate list of links, it's like a list wrapper module Commented Jul 26, 2020 at 9:07
  • a list wrapper that has Link array as it's children Commented Jul 26, 2020 at 9:11

2 Answers 2

2

You can do something like this

const getArrayList = (ItemComponent) => {
    const ListComponent = ({items}) => {
        return <div>{items.map(item => <ItemComponent item={item} />)}</div>
    }   
    return ListComponent
}
Sign up to request clarification or add additional context in comments.

2 Comments

is ListComponent a React component? it has to be a component, it's the assignment requirement actually, it works though but somehow I've to meet the specs, I guess something like dynamic component? The component will receive items prop, like this.props
ListComonent is a functional React component
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.