u111937 u111937 - 5 months ago 15
Javascript Question

Rending multiple elements from database array using .map in a React Component?

I'm learning React and ran into an issue with rendering multiple elements.

The issue is that I am retrieving an Array from Firebase which needs to return a new div and svg for each item in the array. I understand React will only render 1 element so I need to put my content inside a wrapper, which I've done. I've also created a variable that uses .map() to loop through the array and create these elements for me.

What I don't understand, is why is it not returning a new div and svg for each item in the array? Instead, its only creating 1 div and svg? The array contains a list of folder names.

Any help would be appreciated.

class SidebarPrivateFolders extends React.Component {
constructor(props) {
super(props)
}

render() {

let list = this.props.data.map((currentObj) => {
return (
<div>
<svg className="sidebar-icon">
<use xlinkHref={currentObj.xlinkHref}></use>
</svg>
<div className="public-folders">{currentObj.name}</div>
</div>
);
});

return (
<div className="sidebar-section">
<div className="sidebar-section-wrapper">
{list}
</div>
</div>
);
}
}


Console.log(this.props.data) returns the following screenshot.

enter image description here

Answer

In your output.. currentObj.name is an array.. so you've to loop over it as well if you want div to be created for each element inside name array.

You could do something like:

class SidebarPrivateFolders extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {

    let list = this.props.data.map((currentObj) => {
return currentObj.name[0].map((innerArray,i) => { 
      return (
        <div key={i}>
          <svg className="sidebar-icon">
            <use xlinkHref={currentObj.xlinkHref}></use>
          </svg>
          <div className="public-folders">{currentObj.name[i]}</div>
        </div>
      );
    });
    });

    return (
      <div className="sidebar-section">
        <div className="sidebar-section-wrapper">
          {list}
        </div>
      </div>
    );
   }

P.S This is solution is untested. You might get syntax errors