I have one component which is going to display Array of String. The code looks like this:
React.createClass({
render() {
this.props
the <span>{t}</span> you are returning is an object, not a string. Check the react docs about it https://facebook.github.io/react/docs/jsx-in-depth.html#the-transform
By using .join() on the returned array from map, you are joining the array of objects. [object Object], ...
You can put the comma inside the <span></span> so it gets rendered the way you want it to.
render() {
return (
<div>
{ this.props.data.map(
(t,i) => <span>{t}{ this.props.data.length - 1 === i ? '' : ','} </span>
)
}
</div>
)
}
sample: https://jsbin.com/xomopahalo/edit?html,js,output
Update with React 16: It's now possible to render strings directly, so you can simplify your code by removing all the useless <span> tags.
const list = ({ data }) => data.reduce((prev, curr) => [ prev, ', ', curr ]);
The accepted answer actually returns an array of arrays because prev will be an array each time. React is smart enough to make this work, but is it is prone to causing problems in the future such as breaking Reacts diffing algorithm when giving keys to each result of map.
The new React.Fragment feature lets us do this in an easy to understand manner without the underlying issues.
class List extends React.Component {
render() {
<div>
{this.props.data
.map((t, index) =>
<React.Fragment key={index}>
<span> {t}</span> ,
</React.Fragment>
)
</div>
}
}
With React.Fragment we can simply place the separator , outside of the of the returned HTML and React won't complain.
This worked for me:
{data.map( ( item, i ) => {
return (
<span key={i}>{item.propery}</span>
)
} ).reduce( ( prev, curr ) => [ prev, ', ', curr ] )}
function YourComponent(props) {
const criteria = [];
if (something) {
criteria.push(<strong>{ something }</strong>);
}
// join the jsx elements with `, `
const elements = criteria.reduce((accu, elem) => {
return accu === null ? [elem] : [...accu, ', ', elem]
}, null);
// render in a jsx friendly way
return elements.map((el, index) => <React.Fragment key={ index }>{ el }</React.Fragment> );
}
My variant:
{this.props.data
.map(item => <span>{item}</span>)
.map((item, index) => [index > 0 && ', ', item ])}