Split commas in string to <br /> in JSX

15,016

Solution 1

You can try wrap each address in p tag and don't use <br />,

var Component = React.createClass({
    render: function() {
        var addresses = this.props.addresses.split(',').map(function (address, index) {
            return <p key={index}>{ address }</p>; 
        });

        return <div className="addresses">{addresses}</div>;
    }
});

Example

Solution 2

To delimit based on commas, turning commas into line-breaks, while "preferably retaining the commas" (not sure you meant you want to retain them in the output, but interpreting that as such) you can try the following (works for me):

let newAddress = address.split(',').map(line => <span>{line},<br/></span>);
// span tag here only in order for JSX to accept br tag

Solution 3

You can simply insert <br/> between the lines via reduce:

{address.split(',').reduce((all, cur) => [
  ...all,
  <br/>,
  cur
])}

Solution 4

Try using <span> for wrapping the the text and map for generation wrapped jsx,

{ address.split(',').map((addr, idx) => (<span key={idx}>{addr}<br/><span>) }

Solution 5

Try this:

{ address.split( ',' ).map( ( item ) => <> { item } <br /> </>) }

<>...</> is used for JSX to understand that code inside is HTML code.

Share:
15,016
hamishtaplin
Author by

hamishtaplin

Updated on June 27, 2022

Comments

  • hamishtaplin
    hamishtaplin almost 2 years

    I have a string (an address) containing commas that I wish to delimit to line-breaks inside some JSX. Doing the following merely outputs the <br /> as a string:

    {address.split(',').join('<br />')}

    How can I do what I need to do, preferably retaining the commas?

  • olisteadman
    olisteadman over 4 years
    nice! I was able to use this inline without a let. probably not the most idiomatic jsx i've ever written but it's what i (like the OP) was after 👍
  • Brent Washburne
    Brent Washburne over 4 years
    This is closest to using join() because it doesn't add a <br/> to the end of the list