简体   繁体   中英

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>);
        });
    }

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>

Your actual code returns a string when you need a react component :)

This code should work (not tested, might need some ajustments)

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 || []).split(",").map(function(place, i) {
                    return <p key={i}>place</p>
                })}
            </td>
            <td>{order.sortingBufferPlaces}</td>
        </tr>);
    });
}

-EDIT replace

<p>

with whatever needed

<div key={i}>place<br/></div> 

will work too

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM