Skip to content

Instantly share code, notes, and snippets.

@Bwogi
Last active July 14, 2022 20:44
Show Gist options
  • Save Bwogi/8503d5f788edf23a9fbdd726a31ae2e2 to your computer and use it in GitHub Desktop.
Save Bwogi/8503d5f788edf23a9fbdd726a31ae2e2 to your computer and use it in GitHub Desktop.
How to map objects in an array in reactjs

How you actually use the map function and more

With one property

theObject.map((itsSingular) => (<element>{itsSingular.property1}</element>))

With more properties

where property1 is the key

theObject.map((itsSingular) => (
<element key={itsSingular.property1}>{itsSingular.property1}</element>
<element key={itsSingular.property1}>{itsSingular.property2}</element>
<element key={itsSingular.property1}>{itsSingular.property3}</element>
))

Below is its application is its application

This is a simple Nav Component

It has a categories array which has 4 objects

A click function that returns to the console the nae of the category clicked

import React from 'react';

const Nav = () => {
	const categories = [
		{name: 'commercial', description:'Photos of grocery stores, food trucks and other commercial projects'},
		{ name: 'portraits', description: 'Portraits of people in my life' },
		{ name: 'food', description: 'Delicious delicacies' },
		{ name: 'landscape', description:'Farm fields, farm houses, water falls and the beauty of nature'},
	];

	function categorySelected(name) {
		console.log(`${name} clicked!`);
	}

	return (
		<header>
			<h2>
				<a href='/'>
					<span role='img' aria-label='camera'>📸</span> Oh Snap!
				</a>
			</h2>
			<nav>
				<ul className='flex-row'>
					<li className='mx-2'>
						<a href='#about' id='about'>
							About me
						</a>
					</li>
					<li>
						<span>Contact</span>
					</li>
					{categories.map((category) => (
						<li className='mx-1' key={category.name}>
							<span onClick={() => categorySelected(category.name)}>
								{category.name}
							</span>
						</li>
					))}
				</ul>
			</nav>
		</header>
	);
};

export default Nav;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment