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>
    );
  }
}
1
  • You need to wrap each line to a block level element or you can use line break Commented May 22, 2019 at 1:57

3 Answers 3

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>)
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.