Articles → REACT.JS → Display Multiple Instances Of A Component Using Map Function In React.Js

Display Multiple Instances Of A Component Using Map Function In React.Js






Example






import React, { Component } from 'react';
import ReactDOM from 'react-dom';



class ChildComponent extends React.Component {
    render() {
        return <h2>This is {this.props.property} attribute of the child component</h2>;
    }
}

class ParentComponent extends React.Component {
    childComponents = [
        { id: 1, text : "prop 1" },
        { id: 2, text : "prop 2" },
        { id: 3, text : "prop 3" }
    ];

       render() {
        return (
            <div>
                {this.childComponents.map(
                    cp => (<ChildComponent key={cp.id} property={cp.text}/>)
                )}                
            </div>
        );
    }
}

ReactDOM.render(<ParentComponent />, document.getElementById('root'));



Output


Picture showing the output of displaying multiple instances of a component using map function in react.js
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, August 9, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250