Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do an Array.join() with an HTML tag in React, using JSX?

I would like to use the join() method on a Javascript array, but I would like to join() with an HTML tag.

I want to do something like:

class Page extends React.Component {
    render() {
        <p>
           {this.props.the_form['candidate_ids'].map((val,idx) => {
               return this.getCandidateName(val);
           }).join('<br/>')}
        </p>
    }
}

It's escaping the tag and not rendering a new line.

I'm using React, Webpack, and Babel.

like image 768
jhchnc Avatar asked Oct 28 '25 19:10

jhchnc


1 Answers

I have to add this, since dangerouslySetInnerHTML and joining a long string isn't really the react way to do it, and a bit misleading. Plus, you're missing the key on your mapped items

//import Fragment
import { Fragment, Component } from "react"

class Page extends Component {
  const ids = this.props.the_form['candidate_ids'];
  render() {
    <p>
      {ids.map((val, idx) => {
        const name = this.getCandidateName(val);
        return (
          <Fragment key={`${name}${idx}`}>
            {name}
            {idx < ids.length - 1 && <br />}
          </Fragment>
        );
      })}
    </p>
  }
}

(updated to remove the trailing <br/>).

And here's a possible alternate version with no <br/>'s:

class Page extends Component {
  const ids = this.props.the_form['candidate_ids'];
  render() {
    <p>
      {ids.map((val, idx) => {
        const name = this.getCandidateName(val);
        return (
          <span key={`${name}${idx}`} style={{display: 'block'}}>
            {name}
          </span>
        );
      })}
    </p>
  }
}
like image 172
Ted Avatar answered Oct 31 '25 10:10

Ted



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!