Home > Software design >  React - how to 'split' an array to give line breaks
React - how to 'split' an array to give line breaks

Time:01-24

I have an array, let's say:

["One", "Two", "Three"]

And I'd like to render it on separate lines with "<br/>" between them as:

One<br/>Two<br/>Three

so that they'll render as separate lines. When I'd use in a text-based system would be something like:

my_array.join("\n")

So what I want is the equivalent of:

my_array.join(<br/>)

But that doesn't work in something like:

return <div>{my_array.join(<br/>)}</div>;

as it returns objects instead of what I'm looking for:

One[object Object]Two[object Object]Three

Note that I DON'T want a trailing <br/> at the end - I understand I could use a map for that.

CodePudding user response:

I think you can edit the each string array value and put the line break in to it . you need to use map function.


 <div>{my_array.join.map((item, index) => 
                        
                      <span>  {item}<br/></span>
                   )}</div>

CodePudding user response:

Something like this should work:

["One", "Two", "Three"].map((item, index) => {
  if (index === 0) {
    return <>{item}</>
  }
  return <><br/>{item}</>
})

CodePudding user response:

This is how you would do it:


function MyComponent(props) {
    let arr = ["One", "Two", "Three"];
    return (
        <div>
            {[...arr.map(item => <div key={item}>{item}</div>), <br key={'br'}/>]}
        </div>
    );
}

export default MyComponent;

Don't forget that it is important to include a unique key prop for each element in the array to ensure that React can efficiently update the list.

Hope it helped!

  • Related