3

working on a ReactJs project. It is worth noting I am a uni student is very new to react. Part of the code contains an image that can be clicked like a button. Once clicked a react Modal element is opened and the contents of an array are displayed inside

Screen of arrays printed contents

As you will see from the above image, each array item starts with a different number. The issue is all the array elements are printed on one continuous line without spacing inbetween each element.

here is the code for the Modal

<button className="space boxButton button3" onClick={this.openGreenModal}>
  <img className="boxImg" src={greenBox} />
  <div onClick={e => e.stopPropagation()}>
    <Modal className="ModalGreen" isOpen={this.state.greenVisible}>
      <div>
        <img className="boxImgPopUp" src={greenBox} />
        <h1> Green box testing</h1>
        //PRINTING ARRAY ITEMS ON THIS LINE
        <p>Items: {this.state.greenArray}</p>
        <button onClick={this.closeGreenModal}>Close</button>
      </div>
    </Modal>
  </div>
</button>;

is there a way in which I can display each item on a new line?

if anymore code is needed for the project pls do let me know

2
  • Hey Callum! There is nothing in React to "print array items". You will need to wrap each array item to html tags of your choice. Use array.map for it like greenArray.map(v => <p>{v}</p>) Commented Mar 12, 2020 at 18:33
  • @OlegPro exactly what I was looking for thank you! Commented Mar 12, 2020 at 18:37

1 Answer 1

6

Searching for "react render list" put me in the React documentation for exactly this sort of thing: https://reactjs.org/docs/lists-and-keys.html

To give an actual answer though, React is just creating HTML for you so you would want to create HTML tags to render items on different lines just like if you were creating that HTML by hand.

Something like:

{this.state.greenArray.map((item) =>
  <p key={item.something_unique}>{item}<p>
)}
Sign up to request clarification or add additional context in comments.

2 Comments

What if this.state.greenArray is not an array? What if it is some sort of CSV string value?
The question is asking about an array. If you want to deal with some other value, turn it into something iterable first. Maybe with split().

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.