Home > Back-end >  Loop through an array of strings and render it as a Prop in a Component in React
Loop through an array of strings and render it as a Prop in a Component in React

Time:02-28

Questions similar to this were either irrelevant or complicated. I've referred to this SO thread but still not getting my desired output.

Desired output:

Hi there, Anna! 
Hi there, Je!
Hi there, Ram!

I've tried playing around with .map() but only resulted in no output.

Here is the code I've written:

import React from 'react';
import ReactDOM from 'react-dom';

class Greeting extends React.Component {
  render() {
    return <h1>Hi there, {this.props.firstName}!</h1>;
  }
}

const names = ["Anna", "Je", "Ram"];
const greet_em = names.map(name => (<Greeting firstName={name}/>));

ReactDOM.render(
  {greet_em},
  document.getElementById('app')
);

CodePudding user response:

Make sure your separate components' JSX are wrapped within a containing element.

const { Component } = React;

class Greeting extends React.Component {
  render() {
    return <h1>Hi there, {this.props.firstName}!</h1>;
  }
}

const names = ["Anna", "Je", "Ram"];
const greet_em = names.map(name => (<Greeting firstName={name}/>));

ReactDOM.render(
  <div>{greet_em}</div>,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related