Search code examples
javascriptreactjsimageecmascript-6react-component

How to add an image in the first react component and ignore in rest of the components using map function


I'm trying to add content into a component using json file where I require only the first component to have the cover image and rest of the components to ignore it.

Schema:  "TrackList": [
    {
      "CourseNo": "1",
      "CourseName": "C++ Programming with DataStructures",
      "CoverImg":"example.com/cover.jpg"
    },
    {
      "CourseNo": "2",
      "CourseName": "Competitive Programming"
    },
    {
      "CourseNo": "3",
      "CourseName": "Java"
    }
  ]

the below code renders as required but it also adds blank image into components except the first one.

render(){
 const { Data } = this.props;
    const Courses = Data.TrackList.map(course => {
      return (
        <li>
          <span>Course {course.CourseNo}</span>
          <a href='#path-10'>{course.CourseName}</a>
          <img src={course.CoverImg}/>
        </li>
      ) 
    });


return(
 <div className='col-md-4 right-pannel'>
    <ul>
    {Courses}
    </ul>
 </div>
 )
}

Solution

  • Array.prototype.map calls the provided callback function with the current array index (as the second argument). The first index of an array is 0, so you just need to add some logic that makes sure the image is only added when the index is equal to 0, like this:

      const Courses = Data.TrackList.map((course, i) => {
        return (
          <li>
            <span>Course {course.CourseNo}</span>
            <a href='#path-10'>{course.CourseName}</a>
            { i === 0 && <img src={course.CoverImg}/> }
          </li>
          ) 
        });
    

    And here's a slightly modified version of your code turned into a runnable snippet:

    const Data = {"TrackList": [{"CourseNo": "1","CourseName": "C++ Programming with DataStructures","CoverImg":"example.com/cover.jpg"},{"CourseNo": "2","CourseName": "Competitive Programming"},{"CourseNo": "3","CourseName": "Java"}]}
    
    const Courses = Data.TrackList.map((course, i) =>
      <li>
        <span>CourseNo: {course.CourseNo}</span>
        <span> | CourseName: {course.CourseName}</span>
        { i === 0 && <span> | CoverImg: {course.CoverImg}</span> }
      </li>
    );
    
    ReactDOM.render(
      <div className='col-md-4 right-pannel'>
        <ul>
        {Courses}
        </ul>
      </div>,
      document.body
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>