Search code examples
reactjsreact-props

Iterate through 2 lists in Reactjs


I am new to react and I am trying to iterate over 2 lists 'list' and 'link' simultaneously and display the 'list' in a column and hyperlink the address if 'link' is available. Currently my code displays the list in column but I am not sure how to link the URLs to the corresponding list item.

const columnProperties = [
{
    category: 'support',
    list: ['customer_service', 'faq']
},
{
    category: 'connect',
    list: ['facebook', 'instagram', 'twitter', 'youtube'],
    link: ['https://www.facebook.com/', 'https://www.instagram.com/','https://www.twitter.com/', 'https://www.youtube.com/']
}
]


<foot>
{columnProperties.map((props) => {
        return <FooCol key={props.list.toString()} props={props} />
     })}
</foot>


const FooCol = (props) => {

let list = props.props.list;
let category = props.props.category;
let link = props.props.link;

return (
    <Col>
        <ul>
            {list.map((item) => {
                return <li key={item}><a href="">{item}</a></li>                
            })}
        </ul>
    </Col>
)
}

Solution

  • From your code example I assume, that the links and the labels for them (list) are on the corresponding index. So you could map the label array and the link array index by index.

    const FooCol = (props) => {
    
    let list = props.props.list;
    let category = props.props.category;
    let links = props.props.link;
    
    const linksWithLabels = links.map((link, index) => {
      return {
        link: link,
        label: list[index] ?? 'NO LABEL'
      }
    });
    
    return (
        <Col>
            <ul>
                {linksWithLabels.map((item) => {
                    return <li key={item.label}><a href="">{item.link}</a></li>                
                })}
            </ul>
        </Col>
    )
    }
    

    It would be probably better to find a way to receive this information already grouped together beforehand on server side.