Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split elements in array and add line break, then join - Javascript

I'm mapping through data in reactjs. This JSX:

{place.venue.location.formattedAddress}

Is mapping through this axios data request, specially, this array in my response:

formattedAddress: Array(5)
0 : "Chester Rd"
1 : "London"
2 : "Greater London"
3 : "NW1 4NR"
4 : "United Kingdom"

As a result, when I'm mapping, it returns the data, in one sentence, all joined together. Exactly like this:

Serpentine RdHyde ParkGreater LondonW2 2TP

I'm trying to map through, split and join with a line break, but it's not working. My address stops appearing completely. What am I doing wrong?

Here's my code, (I've sliced, so I can remove the country off the end of the address).

{place.venue.location.formattedAddress.slice(0,4).split(',').join('<br />')}
like image 518
Reena Verma Avatar asked Dec 23 '22 06:12

Reena Verma


2 Answers

class App extends React.Component{
  render(){
    var arr = ["hello", "there", "world"]
    return(
      <div>
        {arr.map(s=><React.Fragment>{s}<br/></React.Fragment>)}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById("app"))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="app"></div>

1 You are calling split on array, but it is a string method.

2 You cant use join using '<br />'. jsx will treat it as string.

you should map over your array elements and return an array of jsx.

{place.venue.location.formattedAddress.slice(0,4).map(s=><React.Fragment>s <br/></React.Fragment>)}
like image 176
Anurag Awasthi Avatar answered Dec 25 '22 20:12

Anurag Awasthi


Using map without generating an ending break.

const breakedAttributes = attributes.map((attribute, index) => {
    const isLast = attributes.length === (index + 1);
    return !isLast ? <>{attribute}<br/></> : attribute;
})
like image 39
fabpico Avatar answered Dec 25 '22 20:12

fabpico