Rendering React Components from Array of Objects

Rendering React Components from Array of Objects

When working with React, you may come across a scenario where you need to render a list of components based on an array of objects. This can be achieved by using the map() function in JavaScript to iterate over the array and create a new array of React components.

Let’s say we have an array of objects, each representing a person with their name and age:

const people = [
  { name: "John", age: 25 },
  { name: "Jane", age: 30 },
  { name: "Bob", age: 35 }
];

To render a list of components based on this array, we can use the map() function to iterate over the array and create a new array of React components. Each component will receive the person’s name and age as props:

const PeopleList = () => {
  return (
    
      {people.map((person, index) => (
        
      ))}
    
  );
};

In the above code, we are using the map() function to iterate over the people array. For each person, we are creating a new Person component and passing the person’s name and age as props. We are also assigning a unique key to each component to help React efficiently update the list when needed.

Now let’s define the Person component:

const Person = ({ name, age }) => {
  return (
    
      Name: {name}
      Age: {age}
    
  );
};

The Person component receives the name and age as props and renders them within a

element. You can customize the rendering of each person by modifying the JSX code within the Person component.

Finally, we can render the PeopleList component in our main React component:

ReactDOM.render(, document.getElementById("root"));

This will render the list of components generated from the array of objects inside the element with the ID “root”.

By using the map() function, we can easily render a list of React components from an array of objects. This approach is flexible and allows you to dynamically generate components based on your data.

Here’s the final HTML output:

<

pre>

Rendering React Components from Array of Objects When working with React, you may come across a scenario where you need to render a list of components based on an array of objects. This can be achieved by using the map() function in JavaScript to iterate over the array and create a new array of React components. Let's say we have an array of objects, each representing a person with their name and age: const people = [ { name: "John", age: 25 }, { name: "Jane", age: 30 }, { name: "Bob", age: 35 } ]; To render a list of components based on this array, we can use the map() function to iterate over the array and create a new array of React components. Each component will receive the person's name and age as props: const PeopleList = () => { return ( {people.map((person, index) => ( ))} ); }; In the above code, we are using the map() function to iterate over the people array. For each person, we are creating a new Person component and passing the person's name and age as props. We are also assigning a unique key to each component to help React efficiently update the list when needed. Now let's define the Person component: < pre>const Person = ({ name, age }) => { return ( Name: {name} Age: {age} ); }; </pre&gt Share this:FacebookX Related Posts: Iterate Through Object Properties In JavaScript, objects are a fundamental data type that allow you to store collections of key-value pairs. Often, you may... TS compiler error iterating over type fields TS Compiler Error: Iterating Over Type Fields Published on JS Duck If you are working with TypeScript, you might have... Get Data PhoneNumber from Google API using React OAuht Get Data PhoneNumber from Google API using React OAuth When working with React and OAuth, you may come across the... Mapping data from JSON to Array in Typescript Mapping data from JSON to Array in TypeScript When working with TypeScript, you may often come across the need to...
Posted September 9, 2023 in React by J. Kolby Tags: React Comments Leave a Reply Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Save my name, email, and website in this browser for the next time I comment.
JS Duck Privacy Policy © Copyright 2023
{"prefetch":[{"source":"document","where":{"and":[{"href_matches":"\/*"},{"not":{"href_matches":["\/wp-*.php","\/wp-admin\/*","\/wp-content\/uploads\/*","\/wp-content\/*","\/wp-content\/plugins\/*","\/wp-content\/themes\/twentytwentythree\/*","\/*\\?(.+)"]}},{"not":{"selector_matches":"a[rel~=\"nofollow\"]"}},{"not":{"selector_matches":".no-prefetch, .no-prefetch a"}}]},"eagerness":"conservative"}]} window.WPCOM_sharing_counts = {"https:\/\/js-duck.com\/rendering-react-components-from-array-of-objects\/":2729}; var ce4wp_form_submit_data = {"siteUrl":"https:\/\/js-duck.com","url":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","nonce":"964dae080c","listNonce":"aa145f4b89","activatedNonce":"c6b6d2a485"}; ( function() { var skipLinkTarget = document.querySelector( 'main' ), sibling, skipLinkTargetID, skipLink; // Early exit if a skip-link target can't be located. if ( ! skipLinkTarget ) { return; } /* * Get the site wrapper. * The skip-link will be injected in the beginning of it. */ sibling = document.querySelector( '.wp-site-blocks' ); // Early exit if the root element was not found. if ( ! sibling ) { return; } // Get the skip-link target's ID, and generate one if it doesn't exist. skipLinkTargetID = skipLinkTarget.id; if ( ! skipLinkTargetID ) { skipLinkTargetID = 'wp--skip-link--target'; skipLinkTarget.id = skipLinkTargetID; } // Create the skip link. skipLink = document.createElement( 'a' ); skipLink.classList.add( 'skip-link', 'screen-reader-text' ); skipLink.id = 'wp-skip-link'; skipLink.href = '#' + skipLinkTargetID; skipLink.innerText = 'Skip to content'; // Inject the skip link. sibling.parentElement.insertBefore( skipLink, sibling ); }() ); var hcbVars = {"showCopyBtn":"1","copyBtnLabel":"Copy code to clipboard"}; _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"223076394\",\"post\":\"2729\",\"tz\":\"0\",\"srv\":\"js-duck.com\",\"j\":\"1:14.5\"}") ]); _stq.push([ "clickTrackerInit", "223076394", "2729" ]); wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } ); var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; var dracula = {"homeUrl":"https:\/\/js-duck.com","ajaxUrl":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","pluginUrl":"https:\/\/js-duck.com\/wp-content\/plugins\/dracula-dark-mode","settings":{"excludes":[""],"colorMode":"presets","preset":"dracula"},"isPro":"","upgradeUrl":"https:\/\/js-duck.com\/wp-admin\/admin.php?billing_cycle=annual&page=dracula-pricing","nonce":"49208beb9d"}; var sharing_js_options = {"lang":"en","counts":"1","is_stats_active":"1"}; var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-facebook' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-facebook' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomfacebook', 'menubar=1,resizable=1,width=600,height=400' ); return false; } } ); } )(); var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-x' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-x' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomx', 'menubar=1,resizable=1,width=600,height=350' ); return false; } } ); } )();