0

I have a React component which list items from the Item component.

Below you can see how it looks.

const ListHolder = () => (
  <div>
    <div className="panel">
      <div className="panel-heading">
        <h3 className="panel-title">List Title</h3>
      </div>
      <div className="panel-body">
        <Item
          title="A Title"
          desc="Desc 1."
        />
        <Item
          title="Another Title"
          desc="Desc 2."
        />
        <Item
          title="Some of title"
          desc="Desc 3."
        />
      </div>
    </div>
  </div>
);

export default ListHolder;

Item components are currently hardcoded.

How can I populate / insert the data from some Json data?

1 Answer 1

1

If you pass your items data as props of your component, you could do something like:

const ListHolder = ({items}) => (
  <div>
    <div className="panel">
      <div className="panel-heading">
        <h3 className="panel-title">List Title</h3>
      </div>
      <div className="panel-body">
        { items.map((item) => <Item title={item.title} desc={item.desc} />)}
      </div>
    </div>
  </div>
);

~ EDIT after first comment ~

That is if you can use so called

Otherwise the "usual" way can look something like:

class ListHolder extends React.Component {
  render() {
    const items = [{ "title": "title", "desc": "some desc" }, { "title": "title2", "desc": "some other desc" }];
    return (
      <div>
        <div className="panel">
          <div className="panel-heading">
            <h3 className="panel-title">List Title</h3>
          </div>
          <div className="panel-body">
            { items.map((item) => <Item title={item.title} desc={item.desc} /> )}
          </div>
        </div>
      </div>    
    );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

How I add this example data in a variable before the component? { "title": "title", "desc": "some desc", }, { "title": "title2", "desc": "some other desc", }

Your Answer

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