Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string by newline in react

I have a json string for order.expeditionPlaces which is formatted like:

"expeditionPlaces": "Place1, Place2, Place3"

I am able to split the data but I can't get the string to go onto a new line as html tags are escaped within react

{order.expeditionPlaces ? order.expeditionPlaces.split(",").join("<br>") : ""}

should display:

Place1

Place2

How can I re-write this so the string splits onto new lines?

My current code is

if (this.state.possibleOrders && this.state.possibleOrders.length > 0) {
        this.state.possibleOrders.forEach((order, index) => {
            possibleOrders.push(<tr key={index}>
                <td>{order.orderId}</td>
                <td>{order.orderState}</td>
                <td>{order.expeditionPlaces ? order.expeditionPlaces.split(",").join("<br>") : ""}</td>
                <td>{order.sortingBufferPlaces}</td>
            </tr>);
        });
    }
like image 969
Thomas Harrison Avatar asked Sep 01 '26 11:09

Thomas Harrison


1 Answers

In your case JSX does not interpret "<br />" as a HTML tag, but as a string, so

<td>
{
  order.expeditionPlaces 
    ? order.expeditionPlaces.split(",").join("<br>") 
    : ""
}
</td>

should be

<td>
{
  order.expeditionPlaces 
    ? order.expeditionPlaces.split(",").map(place => <p> {place} </p>) 
    : ""
}
</td>
like image 51
Lyubomir Avatar answered Sep 04 '26 02:09

Lyubomir