user988544
user988544

Reputation: 576

How to loop over values not part of same array in JSX

I am making a component which is fairly simple as far as layout and design goes, it has 3 categories and data associated with it, the layout is pretty much like this:

<div>
  <strong>User Name: </strong>
  {userName}
</div>
<div>
  <strong>User ID: </strong>
  {userID}
</div>
<div>
  <strong>Hobbies: </strong>
  {comma-separated-list}
</div>

Currently all the data is coming from different parts so is not part of a single array or object, and so I can't use .map. The categories are all just constant string values. What is the best way to construct a small component that I can re-use for displaying the data in loop here. Since its pretty much repetition of a div tag with just different data, I would like to reuse the div and just pass the static category names and data associated with those categories.

Upvotes: 1

Views: 50

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104479

Write a simple stateless functional component and pass the required data into props.

Like this:

const DisplayCaterogy = ({ categoryName, categoryValue}) => (
    <div>
        <strong>{categoryName}: </strong>
        {categoryValue}
    </div>
)

Now you need to pass categoryName and categoryValue to component to render the data in dom.

Like this:

<DisplayCaterogy categoryName="User Name" categoryValue={/* name of the user */} />

Note: Don't forgot to export/import the component, if you define that in a separate file.

Upvotes: 1

squgeim
squgeim

Reputation: 2351

You can have something like this:

Data:

data: [
  {
    name: 'Username',
    value: 'Name',
  },
  {
    name: 'Hobbies',
    value: ['one', 'two']
  }
]

And the component:

function ListCategory({ data }) {
  return data.map(category =>
    <Category name={category.name} value={category.value} />
  );
}

function Category({ name, value }) {
  return (
    <div>
      <strong>{name}: </strong>
      {Array.isArray(value) ? value.join(', ') : value}
    </div>
  );
}

<ListCategory data={data} />

Upvotes: 1

Related Questions