user14964079
user14964079

Reputation:

React marking which page i'm on

I'd like for my app to indicate which page I'm currently on. Page numbers get calculated based on the length of an array, and when I move between them, the current page would have a different background. The current page is saved inside the state as well as in local storage.

So I have a CSS class .mark-page {background-color} and I thought I'd just make a ternary inside the button, but it didn't work, however, I'm not sure which parameters to input. Any ideas?

const pageNumbers = [];
for (let i = 1; i <= Math.ceil(allFacts.length / factsPerPage); i++) {
  pageNumbers.push(i);
}

const renderPageNumbers = pageNumbers.map((number) => {
  return (
    <button key={number} id={number} onClick={this.handleClick}>
      {number}
    </button>
  );
});

return <div id="paging">{renderPageNumbers}</div>;

Upvotes: 0

Views: 269

Answers (1)

user14964079
user14964079

Reputation:

@KavinduVindika sure, posting here because it won't let me edit my post:

    class Body extends React.Component {
    constructor() {
        super()
        this.state = {
            isLoading: true,
            allFacts: [],
            currentPage: null,
            factsPerPage: 15,
            error: null,
        }
        this.handleClick = this.handleClick.bind(this)
        }

        componentDidMount() {
        gets API, saves it into state and sets currentPage to 1 if the page had just 
        loaded }

        handleClick(event) {
        
        this.setState ({
            currentPage: localStorage.getItem("currentPage")
        })
        let currentPage = Number(event.target.id)
        localStorage.setItem("currentPage", JSON.stringify(currentPage))
        this.setState ({currentPage: currentPage})
    }

    render() {
        const {allFacts, currentPage, factsPerPage } = this.state
        const indexOfLastFact = currentPage * factsPerPage
        const indexOfFirstFact = indexOfLastFact - factsPerPage
        const allFactsSliced = allFacts.slice(indexOfFirstFact, indexOfLastFact)
        console.log(allFactsSliced)

        const renderAllFacts = this.state.isLoading ? 
        <div id="loading"><h3 className="fact-div" >Please wait.<br/> The cats are disclosing their secrets.</h3></div> :
        allFactsSliced.map((fact, index) => { 
            return <div className="fact-div" key={index}>
            <p className="fact-num">Fact # {(index+1) + (currentPage-1) * factsPerPage}:</p>
            <p className="fact-txt">{fact.fact}</p>
            </div>
        })

hope this is all the important bits

Upvotes: 0

Related Questions