I have one component which is going to display Array of String. The code looks like this:
React.createClass({
render() {
this.props
If I just want to render a comma-separated array of components, I usually find reduce
too verbose. A shorter solution in such cases is
{arr.map((item, index) => (
<Fragment key={item.id}>
{index > 0 && ', '}
<Item {...item} />
</Fragment>
))}
{index > 0 && ', '}
will render a comma followed by a space in front of all array items except the first one.
If you want to separate the second-to-last item and the last one by something else, say the string ' and '
, you can replace {index > 0 && ', '}
with
{index > 0 && index !== arr.length - 1 && ', '}
{index === arr.length - 1 && ' and '}
Use nested array to keep "," outside.
<div>
{this.props.data.map((element, index) => index == this.props.data.length - 1 ? <span key={index}>{element}</span> : [<span key={index}>{element}</span>, ", "])}
</div>
Optimize it by saving the data to array and modify last element instead of checking if its last element all the time.
let processedData = this.props.data.map((element, index) => [<span key={index}>{element}</span>, ", "])
processedData [this.props.data.length - 1].pop()
<div>
{processedData}
</div>