You can also use reduce to insert the separator between every element of the array:

render() {
  let myArray = [1,2,3];
  return (
    <div>
      {
        myArray
          .map(item => <div>{item}</div>)
          .reduce((acc, x) => acc === null ? [x] : [acc, ' | ', x], null)
      }
    </div>
  );
}

or using fragments:

render() {
  let myArray = [1,2,3];
  return (
    <div>
      {
        myArray
          .map(item => <div>{item}</div>)
          .reduce((acc, x) => acc === null ? x : <>{acc} | {x}</>, null)
      }
    </div>
  );
}
Answer from Bless on Stack Overflow
Top answer
1 of 16
251

A simple solution is to use reduce() without second argument and without spreading the previous result:

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}

Without second argument, reduce() will start at index 1 instead of 0, and React is perfectly happy with nested arrays.

As said in the comments, you want to only use this for arrays with at least one item, because reduce() without second argument will throw with an empty array. Normally this should not be a problem, since you want to display a custom message saying something like 'this is empty' for empty arrays anyway.

Update for Typescript

You can use this in Typescript (without type-unsafe any) with a React.ReactNode type parameter on .map():

class List extends React.Component {
  render() {
     <div>
        {this.props.data
          .map<React.ReactNode>(t => <span>{t}</span>)
          .reduce((prev, curr) => [prev, ', ', curr])}
     </div>
  }
}
2 of 16
36

You can use reduce to combine multiple elements of an array:

React.createClass({
  render() {
     <div>
        this.props.data
        .map(t => <span>t</span>)
        .reduce((accu, elem) => {
            return accu === null ? [elem] : [...accu, ',', elem]
        }, null)
     </div>
  }
})

This initializes the accumulator with null, so we can wrap the first item in an array. For each following element in the array, we construct a new array that contains all previous elements using the ...-operator, add the separator and then the next element.

Array.prototype.reduce()

Discussions

How to using array.prototype.join in reactjs - javascript
The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react components by using map and join but I could not. ... The function join is only applicable to an Array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to using array.prototype.join in reactjs
The code looks like this. JohnTomJack I want John Tom Jack. I added e.name.join(" ") but code giving error join is not a function. I try how to render react components by using map and join but I could not. ... The function join is only applicable to an Array. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to join elements in an array within a state variable?
Logging a state variable directly after it's set won't display the correct result because set state is an asynchronous process. Your change function will run to completion before react updates state. The best way, I think, to see the result you're looking for would be as follows: const [problem, setProblem] = useState([ "leaving it all behind", "no tears not time", ]) const change = () => { setProblem((prevProblem) => prevProblem.join()) } useEffect(() => { console.log(problem) },[problem]) change() (On mobile so forgive me if formatting is trash.) So, the reason I choose to operate on a previous state value is to ensure that no other set state operations interfere with my expected result. In this way, I can be certain that I'm joining the version of state that I expect in that moment, regardless of how react chooses to prioritize the asynchronous queue. The reason `useEffect` can capture the state change is because it only runs when an item in its dependency array changes, in this case, `problem`. Now, your function will run, set state, then run the effect and log the new state. More on reddit.com
๐ŸŒ r/learnreactjs
3
3
June 11, 2022
Insert item between every other item in array similar to Array.join
Array.join is useful because it glues together an array of strings by a delimiter taking into account empty arrays and not padding the delimiter at either end of the output string. I am making a R... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
GitHub
gist.github.com โ€บ granmoe โ€บ 274c299b792b039deecfb619753ea32c
Ever wanted to join react children like you join an array? ยท GitHub
import React, { FunctionComponent, ReactNode } from 'react'; export const Separated: FunctionComponent<{ separator?: ReactNode }> = ({ children, separator = ' ' }) => { return ( <> {React.Children.toArray(children) .reduce<ReactNode[]>((previousValue, currentValue) => { return [...previousValue, currentValue, separator]; }, []) .slice(0, -1)} </> ); }; Sign up for free to join this conversation on GitHub.
๐ŸŒ
Codemzy
codemzy.com โ€บ blog โ€บ joining-arrays-react-components
Joining arrays with JSX and React components - Codemzy's Blog
June 9, 2023 - ... I'm going to use my favourite ... in the array, I will add the separator first (ourBreadcrumbIcon). function Breadcrumb({ crumbs }) { return ( crumbs.map((crumb, index) => ( <React.Fragment key={index}> { !!index && ...
๐ŸŒ
GitHub
github.com โ€บ tnhu โ€บ react-join
GitHub - tnhu/react-join: Array.join() for React components - https://codesandbox.io/s/92lr1knk4 ยท GitHub
import ReactJoin from 'react-join' ... <ReactJoin>{links}</ReactJoin> // Join links by a React component <ReactJoin separator={<span>, </span>}>{links}</ReactJoin> // Join links by a closure that returns a React component <ReactJoin ...
Author ย  tnhu
๐ŸŒ
Pluralsight
pluralsight.com โ€บ tech insights & how-to guides โ€บ tech guides & tutorials
Merge Properties of Array Elements with React.js | Pluralsight
September 23, 2020 - This guide shows how to simply loop over a JSON array and merge properties of array elements with JavaScript's advanced array methods `map()` and `filter()`.
Find elsewhere
๐ŸŒ
Altcademy
altcademy.com โ€บ blog โ€บ how-to-join-the-string-in-reactjs-map-function
How to join the string in ReactJS map function - Altcademy.com
November 11, 2023 - The {index < array.length - 1 ? ', ' : ''} part is using a ternary operator to check if the current item is the last in the array. If it's not, it adds a comma and a space after the item. If it is the last item, it adds nothing. You might be wondering why we didn't just use the join() method in our React component.
๐ŸŒ
Bobby Hadz
bobbyhadz.com โ€บ blog โ€บ react-merge-two-arrays
How to merge two Arrays in React.js | bobbyhadz
The same approach can be used to merge two or more arrays when setting the state. ... Copied!import {useState} from 'react'; export default function App() { const initialState = [ {id: 1, name: 'Alice', salary: 100}, {id: 2, name: 'Bobby Hadz', salary: 200}, ]; const [employees, setEmployees] = useState(initialState); const handleClick = () => { const arr = [ {id: 3, name: 'Carl', salary: 300}, {id: 4, name: 'Demi', salary: 400}, ]; // ๐Ÿ‘‡๏ธ merge arrays ๐Ÿ‘‡๏ธ setEmployees([...employees, ...arr]); }; return ( <div> <button onClick={handleClick}>Merge arrays</button> {employees.map(employee => { return ( <div key={employee.id}> <h2>Name: {employee.name}</h2> <h2>Name: {employee.salary}</h2> <hr /> </div> ); })} </div> ); }
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ typescript โ€บ typescript_array_join.htm
TypeScript - Array join()
Python TechnologiesDatabasesComputer ProgrammingWeb DevelopmentJava TechnologiesComputer ScienceMobile DevelopmentBig Data & AnalyticsMicrosoft TechnologiesDevOpsLatest TechnologiesMachine LearningDigital MarketingSoftware QualityManagement Tutorials View All Categories ... TypeScript vs. JavaScript ... TypeScript - null vs. undefined ... separator โˆ’ Specifies a string to separate each element of the array. If omitted, the array elements are separated with a comma. Returns a string after joining all the array elements.
๐ŸŒ
CodeSandbox
codesandbox.io โ€บ examples โ€บ package โ€บ react-join
react-join examples - CodeSandbox
Use this online react-join playground to view and fork react-join example apps and templates on CodeSandbox.
๐ŸŒ
Atomizedobjects
atomizedobjects.com โ€บ blog โ€บ react โ€บ how-to-render-an-array-of-components-in-react
How to render an array of components in React | Atomized Objects
To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-join-method-of-an-array-in-typescript
What is the join() method of an array in TypeScript?
Lines 2โ€“5: We declare three arrays: names, numbers, and cars and initialize them with elements. Line 8: We use the join() method to combine the elements of names using the separator, " ", and print the returned string to the console.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnreactjs โ€บ how to join elements in an array within a state variable?
r/learnreactjs on Reddit: How to join elements in an array within a state variable?
June 11, 2022 -

I've got an array in a state variable and am trying to join the elements into one string. Here's a stripped down version of what I'm trying to do:

I've tried this:

    const [problem, setProblem] = useState(["leaving it all behind", "no tears not time"])

    const change = () => {
    console.log(problem)
    setProblem(problem.join())
    console.log("joined", problem)
    }

and this

    const [problem, setProblem] = useState(["leaving it all behind", "no tears not time"])

    const change = () => {
	console.log(problem)
	    const solution =  problem.map(arr => arr.join(','))
	console.log("joined", problem, solution)
    }

They both don't work. I'm trying to get to the point where problem is "leaving it all behind no tears not time"

๐ŸŒ
Medium
medium.com โ€บ @glasshost โ€บ how-to-merge-two-arrays-in-react-js-ce01cdd163e5
How to Merge Two Arrays in React.js | by Glasshost | Medium
April 16, 2023 - Another way to merge two arrays in React.js is by using the `concat()` method. The `concat()` method is used to merge two or more arrays into a new array.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ typescript-array-join-method
TypeScript Array join() Method - GeeksforGeeks
July 12, 2024 - The Array.join() method in TypeScript is a built-in function used to join all the elements of an array into a single string.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 54080924 โ€บ how-to-join-array-in-fetch-request-with-different-variable-types-in-react โ€บ 54081881
reactjs - How to join array in fetch request with different variable types in React? - Stack Overflow
class Record extends Component { constructor(props) { super(props) this.state = { data: [] } } componentDidMount() { fetch('http://127.0.0.1:9200/_index/_doc/1') .then(res => res.json()) .then(json => this.setState({data: json._source})) } render() { const data = this.state.data const record = Object.keys(data).map((f, i) => { return <li key={i}>{f} : {typeof data[f] === 'object' ?...
๐ŸŒ
MDN Web Docs
developer.mozilla.org โ€บ en-US โ€บ docs โ€บ Web โ€บ JavaScript โ€บ Reference โ€บ Global_Objects โ€บ Array โ€บ join
Array.prototype.join() - JavaScript - MDN Web Docs
The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.