Daniel Zhang
Daniel Zhang

Reputation: 217

How to display array of text in react?

I'm making a portfolio website in ReactJS. I'm trying to display an array of text under desc in HomePageContent.js. I'm not sure how display each of the paragraphs. I think I have to map the paragraphs, but I'm not sure how to do that.

Relevent Code

HomePageContent.js

// Image import statements
import Im1 from '../img/Im1.png';
import Im2 from '../img/Im2.jpg';
import Im3 from '../img/Im3.jpg';

let HomePageContent = {
  job: [{
    logo: Im1,
    alt: 'Logo1',
    companyName: 'comp1' ,
    link: 'link1',
    title: 't1',
    duration: 'dur1',
    location: 'loc1',
    desc: {
      text: 'p1',
      text: 'p2',
      text: 'p3',
      text: 'p4'
    },
    id: 1
  }

export default HomePageContent;

Job.js

import React from 'react';

import '../css/Experience.css';

function Job(props) {
  console.log(props.name);
  const jobList = props.job.map(j =>
    <div className='exp-container'>
      <img src={j.logo} alt={j.alt} />
      <div className='description'>
        <div>
          <a href={j.link} rel='noopener noreferrer' target='_blank'>
            {j.companyName}
          </a>
        </div>
        <div>{j.title}</div>
        <div>{j.duration}</div>
        <div>{j.location}</div>
        <div><p>{j.desc}</p></div>
      </div>
    </div>
  )

  return (
    <div>{jobList}</div>
  );
}

export default Job;

Upvotes: 2

Views: 11034

Answers (1)

Kevin Hoopes
Kevin Hoopes

Reputation: 507

You're right, mapping over the paragraphs would work, but I recommend changing the value inside desc to an array so that you have an easier time doing that.

...
desc: [
      'p1',
      'p2',
      'p3',
      'p4',
    ],
...

Then, in your JSX, you can map over it and put each of them in their own set of <p> tags.

<div>
   {j.desc.map(paragraph => <p>{paragraph}</p>)}
</div>

This works because the map function returns an array of whatever you return in the provided fat arrow function, and JSX will automatically render an array of JSX elements one right after the other. So it looks like this in the rendered HTML:

<div>
   <p>p1</p>
   <p>p2</p>
   <p>p3</p>
   <p>p4</p>
</div>

Upvotes: 1

Related Questions