Table is not Rendering in React

Why isn’t my code working?

export const movies = [
  {
    _id: "5b21ca3eeb7f6fbccd471815",
    title: "Terminator",
    genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
    numberInStock: 6,
    dailyRentalRate: 2.5,
    publishDate: "2018-01-03T19:04:28.809Z"
  },
  {
    _id: "5b21ca3eeb7f6fbccd471816",
    title: "Die Hard",
    genre: { _id: "5b21ca3eeb7f6fbccd471818", name: "Action" },
    numberInStock: 5,
    dailyRentalRate: 2.5
  }
];

In movies.js

import React from 'react';
import {movies} from '../services/fakeMovieService';

class Movies extends React.Component {
	constructor(props) {
		super(props);

		this.tableFormat = this.tableFormat.bind(this);
	}

tableFormat() {
	movies.map((movie) => {
		return (
			<tr>
				<td>{movie.title}</td>
			</tr>
			);
	});
}


	render() {
		return (
			<table className="table">
			  <thead>
			  <tr>
			    <th>Title</th>
			    <th>Genre</th> 
			    <th>Stock</th>
			    <th>Rate</th>
			  </tr>
			  </thead>
			  <tbody>
				{this.tableFormat()}
			  </tbody>
			</table>

			);
	}
}

export default Movies;

It’s not giving any error but the movies aren’t showing either.

@umairhp

tableFormat() { 
  movies.map((movie) => {
     return ( 
          <tr>
              <td>{movie.title}</td>
          </tr>
      ); 
  }); 
}

This function does not return anything. Return from map modifies “movies” array, but after that function does not return anything.
So this part:
{this.tableFormat()}
Will just modify movies array and that is it.

1 Like

Oh thanks a lot. How could I forget. Here’s what I did now:

tableFormat() {
	return movies.map((movie) => {
		return (
			<tr>
				<td>{movie.title}</td>
			</tr>
			);
	});
}

But when I try to do this:

tableFormat() {
	return movies.map((movie) => {
		return (
			<tr>
				<td>{movie.title}</td>
				<td>{movie.genre}</td>
				<td>{movie.numberInStock}</td>
				<td>{movie.dailyRentalRate}</td>
			</tr>
			);
	});
}

I am getting this error:
Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead.

Do you have codepen or something?

No I have installed React on my local PC.

There might be a possibility that movie.title, movie.genre, movie.numberInStock or movie.dailyRentalRate is an Object. Have you double checked your data? Are they strings/numbers?

Also, add a key prop to the <tr>, although it is not related to the current error that you’re having.

Edit: Sorry, I didn’t see your initial code. movie.genre is an object indeed. Just access it’s name property!

Read the errors, they are usually pretty self-explanatory!

1 Like

Thanks. That solved my problem. but how did you figure this out? The error didn’t mention that it was an object.

Oh yes iI see it now. Thanks a lot for this. I am new to React and it’s a bit overwhelming for me.

Glad to hear that you figured that out. Good work, keep it up.