How to render react components by using map and join?

后端 未结 14 2201
南旧
南旧 2020-12-07 15:30

I have one component which is going to display Array of String. The code looks like this:

React.createClass({
  render() {
     
this.props
14条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 16:07

    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) => (
      
        {index > 0 && ', '}
        
      
    ))}
    

    {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 '}
    

提交回复
热议问题