Converting an Array of Strings to HTML in React

Hi, can anyone help me with the proper way to iterate over an array of strings, that will then be placed in a paragraph tag using Reactjs?

The array looks something like:

names = [ 'James', 'Susan', 'Frank' ];

Here is my react component called “Riders” (I’ve added comments for help on what I’m trying to do):

import React from 'react';

import { Drivers } from '../api/drivers';

// The 'this.props.names' contains an array of names: ["John", "Susan", "John"].
// How would I iterate over the array, pull the names from this array, and then 
// have those names rendered in a paragraph tag in a manner like:
// <p>John - Susan - John</p>

// So far I've attempted using template strings and the braces, {} , javascript
// injection. Doing this renders an empty paragraph. Please let know of the proper 
// way to complete this task. Any help would be greatly appreciated. :)     

export default class Riders extends React.Component {
  renderNames() {
    let empty = ``
    let names = this.props.names;
    let namesLength = names.length;
    for (var i = 0; i < namesLength; i++) {
      empty[i] = empty + `-` + ` ${empty[i]}`
    }
    return empty;
  }
  render() {
    return (
      <div>
        <p>{this.renderNames}</p>
      </div>
    );
  }
}

use names.join('-') is enough:

names = [ 'James', 'Susan', 'Frank' ]
names.join('-') // James-Susan-Frank
2 Likes

Thank you for answering this! If anyone else has further insight, please feel free to add. :smile:

Yo, just wanted to confirm that it works now. Thank you for shedding light on the use of “join()”. This also cleaned up the code in addition to saving me from having to iterate through the array. Kudos to your response time as well!

This is the updated component:

export default class Riders extends React.Component {
  renderNames() {
    let names = this.props.names;
    return names.join(' - ');
  }
  render() {
    return (
      <div>
        <p>{this.renderNames()}</p>
      </div>
    );
  }
}