3

I needed to print a string, "dummy data".

So I made a function that returns array which has string "dummy data" in it. I was able to print "dummy data dummy data dummy data ...". However, I want to put newline each string. Then it will looks like,

...
dummy data
dummy data
dummy data
...

How can I do it?

Sample image of code and result

class Content extends Component {
  dummyDataLoop = () => {
    var rows = [];
    for (let i = 0; i < 10; i++) {
      rows.push("dummy data");
    }
    return rows;
  };

  render() {
    return (
      <article>
        <div>[CONTENT AREA START]</div>
        {this.dummyDataLoop()}
        <div>[CONTENT AREA END]</div>
      </article>
    );
  }
}
Mason YM Koh
  • 324
  • 2
  • 10

3 Answers3

2

Wrap the string in a <div> and then push it into array.

dummyDataLoop = () => {
  var rows = [];
  for (let i = 0; i < 10; i++) {
    rows.push(<div>dummy data</div>);
  }
  return rows;
};

Another way is to use map() and spread operator to shorten the code.

dummyDataLoop = () => [...Array(10)].map(x => <div>dummy data</div>)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • @MasonYMKoh Glad to help you. Also see the second of doing the same thing. Actually creating an empty array and pushing elements to it is not considered a clean code. – Maheer Ali May 22 '19 at 02:02
0

You can wrap dummy data with div tag before pushing it to array like this

<div>dummy data</div>

You can change your code to,

dummyDataLoop = () => {
    var rows = [];
    for (let i = 0; i < 10; i++) {
      rows.push(<div>dummy data</div>);   // notice change in this line
    }
    return rows;
};

  render() {
    return (
      <article>
        <div>[CONTENT AREA START]</div>
        {this.dummyDataLoop()}
        <div>[CONTENT AREA END]</div>
      </article>
    );
  }
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

This is much simple. Use map to iterate the array then return it wrapped in a

tag.

class Content extends Component {
  dummyDataLoop = () => {
    var rows = [];
    for (let i = 0; i < 10; i++) {
      rows.push("dummy data");
    }
    return rows;
  };
  render() {
    return (
      <article>
        <div>[CONTENT AREA START]</div>
        {this.dummyDataLoop().map((item, index) => <p key={index}>{item}</p>)}
        <div>[CONTENT AREA END]</div>
      </article>
    );
  }
}
Ken Labso
  • 885
  • 9
  • 13