Zahid Hussain
Zahid Hussain

Reputation: 1121

Display values of two different arrays in react component

I am building a react app which will display courses and authors, both courses and authors array's i have to display the list of courses and their corresponding authors. i have used the array map method to map over all courses and display them but i am getting stuck how to display the corresponding authors. below is my code

    import React from "react";
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
import { toast } from "react-toastify";

function CourseList(props) {
  return (
    <table className="table">
      <thead>
        <tr>
          <th>&nbsp;</th>
          <th>Title</th>
          <th>Author Name</th>
          <th>Category</th>
        </tr>
      </thead>
      <tbody>
        {props.courses.map(course => {
          return (
            <tr key={course.id}>
              <td>
                <button
                  className="btn btn-outline-danger"
                  onClick={() => {
                    props.deleteCourse(course.id);
                    toast.success("Course Deleted");
                  }}
                >
                  Delete
                </button>
              </td>
              <td>
                <Link to={"/course/" + course.slug}>{course.title}</Link>
              </td>
              <td>{props.authors.name}</td>
              <td>{course.category}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

CourseList.propTypes = {
  deleteCourse: PropTypes.func.isRequired,
  courses: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.number.isRequired,
      title: PropTypes.string.isRequired,
      authorId: PropTypes.number.isRequired,
      category: PropTypes.string.isRequired
    })
  ).isRequired
};

export default CourseList;

below is my response Json enter image description here

could anyone please help me in displaying the author name in author name cell.

Upvotes: 0

Views: 145

Answers (2)

Barun Patro
Barun Patro

Reputation: 860

well.. looking at your JSON response.. this could work.

<td>{props.authors.find(author => author.id === course.authorId).name}</td>

Upvotes: 1

akhtarvahid
akhtarvahid

Reputation: 9779

Change <td>{props.authors.name}</td> to <td>{course.authors.name}</td>

don't need to use props for that because you are accessing from array so just access object field of array.

If course.authors.name not found just console your author name and then access that

Upvotes: 0

Related Questions