Reputation: 93
I want to render a list of elements from an array of objects in react. However, it's not working properly.
My Datafile
export const PageBottomData = [
{
sectionName: "property1",
listOfLinks: [
{linkName: "value1", linkStatus: "inactive"},
{linkName: "value2", linkStatus: "inactive"},
]
},
{
sectionName: "property2",
listOfLinks: [
{linkName: "value1", linkStatus: "inactive"},
{linkName: "value2", linkStatus: "inactive"}
]
},
];
Though the data has been imported correctly( from console log), the data is not returned to the render method. I want to render a list of links whose name is taken from linkName attribute.
App.js
import React from 'react';
import {PageBottomData} from './PageBottomData';
class App extends React.Component {
sectionListGroup = (keyword) => {
const listItems = PageBottomData.map(item => {
if(item.sectionName === keyword)
item.linkOfList.map((link, idx) => {
<li key = {idx} className = "list-group-item">link.linkName</li>
})
});
return listItems;
}
render() {
return (
<ul className = "list-group list-group-flush">
{sectionListGroup("Discover")}
</ul>
);
}
export default App;
Error: 'sectionListGroup is undefined'
Upvotes: 2
Views: 216
Reputation: 405
You had some minor error in your method "sectionListGroup", I updated method with correction.
sectionListGroup = (keyword) => {
const listItems = PageBottomData.map(item => {
if(item.sectionName === keyword)
{
return item.listOfLinks.map((link, idx) => {
return <li key = {idx} className = "list-group-item">{link.linkName}</li>
})
}
});
return listItems;
}
Also in the test example your not calling the method properly with right argument i.e {sectionListGroup("Discover")}
.
As we can see you are not having any data with the value "Discover", so check with other values you will get the answer.
Upvotes: 0
Reputation: 1450
Each map
needs return statement
const PageBottomData = [
{
sectionName: "property1",
listOfLinks: [
{ linkName: "value1", linkStatus: "inactive" },
{ linkName: "value2", linkStatus: "inactive" },
],
},
{
sectionName: "Discover",
listOfLinks: [
{ linkName: "value1 ", linkStatus: "inactive" },
{ linkName: "value2 ", linkStatus: "active" },
],
},
];
class App extends React.Component {
sectionListGroup = (keyword) => {
return PageBottomData.map((item) => {
if (item.sectionName === keyword)
return item.listOfLinks.map((link, idx) => {
return (
<li key={idx}>
{link.linkName} - {link.linkStatus}
</li>
);
});
});
};
render() {
return <ul>{this.sectionListGroup("Discover")}</ul>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1