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.
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>
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With