TheBetterJORT TheBetterJORT - 3 months ago 11
React JSX Question

No errors can't return data from map function?

In the browser console I get the object. But when I try and return just the text, link, title nothing returns. I get the object in the console, but when I try and add .text or .link the page shows blank. The console shows no errors.

import React, { Component } from 'react';

class Navigation extends Component {

getLinks = (object) => {
Object.keys(object).map((property, i) => {
const { text, title } = object[property][i];
console.log(object[property][i])
return (
<ul>{title}
<li>{text}</li>
</ul>
)
});


}
render() {


let { items } = this.props;
return (

<div>
<ul>
{this.getLinks(items)}
</ul>
</div>

);
}
}

export default Navigation;


JSON

const navigation = {
pageInfo: [
{title: "A title"},
{text: "item 1", link: "https://google.com"},
{text: " item 2", link: "https://googleconquestio.com"}
],
pageInfo2: [
{title: "A title"},
{text: "item 1", link: "https://google.com"},
{text: "item 2", link: "https://googleconquestio.com"}
],
pageInfo3: [
{title: "Applications"},
{text: "application item 1", link: "https://google.com"},
{text: "application item 2", link: "https://googleconquestio.com"}
]
}

Answer

A couple things are happening. First you are not returning the newly created array that map returns. Second you will also need to loop through each of your keys in your navigation object since they are arrays. You are trying to grab {title, text} from object[property][i], but that won't work since title is at index 0 and text is at index 1. I would recommend re-structuring your data.

You could do something like this:

const navigation = [
    {
        title: 'Title 1',
        text: [
            { 
                name: 'item 1',
            },
            {
                name: 'item 2',
            }
        ],
    },
    {
        title: 'Title 2',
        text: [
            { 
                name: 'item 1',
            },
            {
                name: 'item 2',
            }
        ],
    }
];

return navigation.map(obj => {

    let listElements = obj.text.map((li, c) => {
        return (
            <li key={c}>{li.name}</li>
        );
    });
    return (
        <ul>
            {obj.title}
            {listElements}
        </ul>
    );
});