neel
neel

Reputation: 27

In ReactJS, rendering breaks after using a child component

This is the App Component:

import React, { Component } from 'react';
import { getMovies } from './Files/FakeMovieAPI';
import ItemsNumbers from './Pagination/ItemsNumber';
import Table from './Pagination/Table';

class App extends Component {
  state = {
    movies: getMovies()
  }
  render() {
    return (
      <div className="App">
        <h2 className="d-inline bg-success"> Motion Pictures Stall </h2>
        <Table movies={this.state.movies} />
        <ItemsNumbers items={this.state.movies} />
      </div>
    );
  }
}

export default App;

The ItemsNumbers Component: I wish to use this component to count the numbers of items in the movies(which is being passed as a props) and return the count.

import React, { Component } from 'react';

class ItemsNumber extends Component {
    state = {
        movies: this.props
    }
    count = 0;
    ItemsCounting = () =>{
        const length = this.state.movies.length()
        console.log(length)
    }

    render(props) {
        return (
            <div>
                {this.ItemsCounting()}
            </div>
        );
    }
}

export default ItemsNumber;

The FakeMovieAPI file:

const Movies = [
  {
    id: 'm7pbc81a',
    title: 'Matrix',
    Year: 1999,
    genre: { id: '193x', name: 'Sci-fi' },
    ratings: 8.7,
    cost: 15
  },
....... 
]
export function getMovies() {
  return Movies;
}

Now the errors I am facing: (passing a link to the screenshot error)

TypeError: this.state.movies.length is not a function
ItemsNumber.ItemsCounting
http://localhost:3000/main.577acc89bd7fb431ffe6.hot-update.js:32:40
this.count = 0;
this.ItemsCounting = () => {
const length = this.state.movies.length();
^
console.log(length);
};
}
View source
ItemsNumber.render
http://localhost:3000/main.577acc89bd7fb431ffe6.hot-update.js:39:22

render(props) {
return /#PURE/Object(react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_1__["jsxDEV"])("div", {
children: this.ItemsCounting()
^
}, void 0, false, {
fileName: _jsxFileName,
lineNumber: 15,

Error Screenshot:

Upvotes: 0

Views: 140

Answers (1)

Andy
Andy

Reputation: 63514

length is a array property, not a function.

Use

const length = this.state.movies.length;

or use destructuring assignment:

const { length } = this.state.movies;

Additionally ItemsNumber doesn't require its own state. Simply return the length of the array that you pass in as a component property.

Be mindful that when you use a real asynchronous call to an API you'll have to check that the movies array exists first.

class ItemsNumber extends Component {

  render(props) {

    const { length } = this.props.movies;

    if (!length) return <div />;

    return <div>{length}</div>;

  }

}

Upvotes: 1

Related Questions