joy08
joy08

Reputation: 9652

Unable to setState inside child component using the value passed by Parent

I am having this situation where I am implementing a Pagination component to which I am passing the length from the parent component. I am unable to print the page numbers in this child component. It is throwing "Maximum depth reached"

https://codesandbox.io/s/focused-benz-kfn9q

Can someone help me here?

Parent

import React from "react";
import ReactDOM from "react-dom";
import Pagination from "./Pagination";

import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      length: 0
    };
  }

  componentDidMount() {
    this.setState({ length: 99 });
  }

  render() {
    return <Pagination dataCount={this.state.length} />;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Child

import * as React from "react";

export default class Pagination extends React.Component {
  componentDidMount() {
    console.log(this.props);
  }

  renderPageNumbers = () => {
    const numberOfPages = Math.ceil(this.props.dataCount / 10);
    let pages = [];
    for (let i = 1; i < numberOfPages; i++) {
      pages.push(<span key={i}>{i}</span>);
    }
    this.setState({ pages });
  };

  render() {
    return <>{this.renderPageNumbers()}</>;
  }
}

Upvotes: 0

Views: 92

Answers (2)

Shan
Shan

Reputation: 619

import * as React from "react";

export default class Pagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pages: this.findNumberOfPages()
    };
    this.findNumberOfPages = this.findNumberOfPages.bind(this)
  }
  componentDidMount() {
    console.log(this.props);
  }
  componentDidUpdate(prevProps) {
    if(prevProps.dataCount != this.props.dataCount){
      this.setState({ pages: this.findNumberOfPages() });
    }
  }

  findNumberOfPages() {
    return Math.ceil(this.props.dataCount / 10);
  }

  renderPageNumbers = () => {
    const numberOfPages = this.findNumberOfPages()
    let pages = [];
    for (let i = 1; i <= numberOfPages; i++) {
      pages.push(<span key={i}>{i}</span>);
    }
    return pages;
  };

  render() {
    return (
      <>
        {this.props.currentPage > 1 ? <span>Prev</span> : ""}
        {this.renderPageNumbers()}
        {this.props.currentPage < this.state.pages ? <span>Next</span> : ""}
      </>
    );
  }
}

I hope this helps.

Upvotes: 1

NN796
NN796

Reputation: 1267

You need to return pages from renderPageNumbers function. For example,

renderPageNumbers = () => {
    const numberOfPages = Math.ceil(this.props.dataCount / 2);
    let pages = [];
    for (let i = 1; i < numberOfPages; i++) {
      pages.push(<span key={i}>{i}</span>);
    }
    return pages;
    // this.setState({ pages });
  };

CodeSanbox link is listed here

Let me know if this worked.

Upvotes: 3

Related Questions