components not rendering in react-paginate - javascript

I am trying to implement react pagination on local json data, using react-paginate. The buttons are clickable and the css works fine. However, any components after the first page are not being rendered. The entire page (except for the header) goes blank. The pagination buttons were the only components visible at first, but once I applied some styling to the buttons, they vanished as well (just basic styling like background colours etc). Now nothing is displayed unless I'm on the first page of cards displayed. Can you please help me with this issue?
This is my dashboard.tsx
import React, { useState } from 'react'
import logo from '../assets/logo192.png'
import courses from '../data/courses.json'
import star_on from '../assets/star_on.png'
import star_off from '../assets/star_off.png'
import next from '../assets/next.png'
import left_arrow from '../assets/left-arrow.png'
import right_arrow from '../assets/right-arrow.png'
import ReactPaginate from 'react-paginate'
function Dashboard(this: any) {
let on = false
const turnOn = (event: any) => {
if (on)
{event.target.src = star_off
on = false
}
else {
event.target.src = star_on
on = true
}
}
const [cards, setCards] = useState(courses)
const [pageNumber, setPageNumber] = useState(0)
const cardsPerPage = 6
const pagesVisited = pageNumber * cardsPerPage
const displayCards = cards
.slice(pagesVisited, pagesVisited + cardsPerPage)
.map(card => {
return (
<div className='dashboard--card'>
<div className='line1'>
<div><img src ={card.image} alt ="course" className='card--image'></img></div>
<div className='card--title'>{card.title}</div>
<div className='card--author'>{card.author}</div>
<div> <img className='card--star' src={star_off} alt="star" onClick={turnOn} /></div>
<div className='card--price'>Rs {card.price}/-</div>
<div className='card--discounted'>Rs {card.discounted}/-</div>
<div className='card--cartbtn'> ADD TO CART</div>
<img className='card--arrow' src ={next} alt ="arrow"/>
</div>
<div className='line2'>
<div className='reactbtn'>React</div>
<div className='reactbtn'>React</div>
</div>
</div>
)
})
const pageCount = Math.ceil(cards.length / cardsPerPage)
const changePage = (selected: React.SetStateAction<number>) => {
setPageNumber(selected)
}
return (
<div className='dashboard--main'>
<div className='dashboard--banner'>
<div className='dashboard--banner-title'>
Discover Latest Courses on React
</div>
<div className='dashboard--banner-logo'>
<img src={logo} alt ="react-logo" className='react-logo'/>
</div>
</div>
<div className='dashboard--items'>
<div className='dashboard--left'>
<p className='dashboard--all-courses'>All courses</p>
<div className='dashboard'>
{displayCards}
<div className='dashboard--paginate'>
<ReactPaginate
previousLabel= {<img className='paginate--arrow-left' src ={left_arrow} alt ="prev"/>}
nextLabel = {<img className='paginate--arrow-right' src ={right_arrow} alt ="next"/>}
pageCount={pageCount}
onPageChange ={changePage}
containerClassName ={"paginationBtns"}
pageLinkClassName={"pageBtns"}
previousLinkClassName ={"prevBtn"}
nextLinkClassName ={"nextBtn"}
disabledClassName ={"disabledBtn"}
activeClassName ={"activeBtn"}/>
</div>
</div>
</div>
<div className='dashboard--right'>
hello
</div>
</div>
</div>
)
}
export default Dashboard
App.tsx
import React from 'react';
import Dashboard from './components/Dashboard';
import Wishlist from './components/Wishlist';
import Error from './components/Error';
import Cart from './components/Cart';
import Profile from './components/Profile';
import logo from './assets/logo.png'
import cart from './assets/cart.svg'
import profile from './assets/profile.svg'
import { BrowserRouter,Routes,Route, NavLink} from 'react-router-dom';
import './App.css';
function App() {
return (
<BrowserRouter>
<nav className='navbar'>
<li><NavLink to="/"><img className='navbar--logo' src={logo} alt ="Dashboard"/></NavLink></li>
<div className='navbar--links'>
<li><NavLink className="single" to="/">COURSES</NavLink></li>
<li><NavLink className="single" to ="/wishlist">MY WISHLIST</NavLink></li>
</div>
<div className='navbar--icons'>
<li><NavLink className='navbar--cart' to="/cart"><img src={cart} alt ="Cart"></img></NavLink></li>
<li><NavLink className='navbar--profile' to="/profile"><img src={profile} alt ="profile"></img></NavLink></li>
</div>
</nav>
<Routes>
<Route path='/' element={<Dashboard/>}/>
<Route path='wishlist' element={<Wishlist/>}/>
<Route path ='cart' element={<Cart/>}/>
<Route path ='profile' element ={<Profile/>}/>
<Route path='*' element={<Error/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
The other pages in App.tsx haven't been implemented yet, they only display basic components, and they they don't interfere with the working of dashboard.tsx. I don't know why the previously rendrered pagination buttons are vanishing. I have tried to inspect my code, and changed the values of the number of cards rendered per page. No matter the number, only the page is rendered. If someone has gone through this before and/or has a solution to this, that would be great.

I resolved the question! I hadn't destructured the 'selected' object while accessing it in my changePage function. Hope this is useful for anyone else who comes across this issue in the future

Related

pass in props into component to render

// Warning: Cannot read properties of undefined (reading 'params')
// im try to get movie_id from movielist.js to view single movie on movie.js onclicking view review
// basically my error is from inability to pass the props into movie.js
//in nav/index.js
import { BrowserRouter as Router, Routes, Route, useParams} from "react-router-dom";
import Navbar from './navbar';
import MovieList from "../components/movie-list"
import Movie from "../components/movie"
const Nav = () => {
return (
<Router>
<Navbar/>
<Routes>
<Route exact path={'/'} element={<MovieList/>}/>
<Route path='/movies/:id/' element={<Movie props={useParams()} />} />
</Routes>
</Router>
)}
//in movielist.js
import React, {useState, useEffect} from 'react'
import MovieDataService from "../services/movie"
import { Link } from 'react-router-dom'
const MovieList = () => {
....
return (
<div>
....
<div>
{movies.map((movie)=>{
return(
<div className="card" key={movie._id}>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px180"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<h2>Rating:{movie.rated}</h2>
<p>{movie.plot}</p>
<Link to={"/movies/"+movie._id}>View Review</Link>
</div>
</div>
</div>
);
})}
</div>
</div>
)
}
// in movie.js
import React, { useState, useEffect } from 'react'
import MovieDataService from '../services/movie'
import { Link } from 'react-router-dom'
const Movie = (props) => {
useEffect(()=>{
getMovie(props.match.params.id)
},[props.match.params.id]) //won't call getMovie Multiple times unless id is updated.
return (
<div>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px250"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<p>{movie.plot}</p>
{props.user && <Link to={"/movies/"+props.match.params.id+"/review"}>Add Review</Link>
}
</div>
</div>
);
})}
</div>
</div>
)
}
Use useParams() hook to get url params.
const {id} = useParams()
useEffect(()=>{
getMovie(id)
},[id])
replace props.match.params.id with id everywhere

Router for specific component is not woking

I want to route specific component in other component but when I click on the link other components are disappeared
import React from 'react';
import { Route, Switch, BrowserRouter } from 'react-router-dom';
import Sidebar from '../componants/Sidebar'
import Navbar from '../componants/Navbar';
import Router from '../Routers/Routers'
import Answer from './Answer';
import Feed from './Feed'
const Layuot = () => {
return (
<>
<div className="container-fluid">
<Navbar />
<div className="rows row">
<div className='col-3'>
<Sidebar/>
</div>
<div className="col-9 ">
<div className="content">
<Switch>
<Route path='/feed'><Feed/></Route>
<Route path = '/answer/:q_id'><Answer/></Route>
</Switch>
</div>
</div>
</div>
</div>
</>
)
}
export default Layuot;
see output
enter image description here
See Url
enter image description here
Every component are disappeared and Feed component not ms

How to run animation only once while current session?

I have a website page that uses react-anime and react-typing-animation. My issue is to animate some elements displayed on it only once while the current session. So, if my site was opened on the main page, the animation would launch, and then, after switching a few pages and returning back to the main page, the animation wouldn't be executed again.
I've thought about sessionStorage, but I don't understand how to use it with these libraries.
Here's all the code:
index.js
import React from 'react'
import styles from './Index.module.css'
import Greeting from '../components/main/Greeting'
import Yelnya from '../components/main/Yelnya/Yelnya'
import BlueLakes from '../components/main/BlueLakes'
import Gallery from "../components/main/Gallery";
export default function Home() {
return (
<div className={styles.container}>
<Greeting />
<Yelnya />
<BlueLakes />
<Gallery />
</div>
)
}
Greeting.js
import React from 'react'
import styles from './Greeting.module.css'
import Tag from './Tag'
import Anime from "react-anime";
import Typing from "react-typing-animation"
export default function Greeting() {
return (
<div className={styles.root}>
<div className={styles.title}>
<Typing startDelay={50} speed={100}>
Explore Belarusian nature with us.
</Typing>
</div>
<div className={styles.hint}>
<Anime
opacity={[0,1]}
translateX={[-50,0]}
duration={3000}
delay={4200}
>
<p className={styles.hintTitle}>Go to:</p>
</Anime>
<Tag title="#Yelnya" link="/#yelnya" delay={4400}/>
<Tag title="#Blue lakes" link="/#blue-lakes" delay={4500}/>
<Tag title="#Galleries" link="/#galleries" delay={4600}/>
</div>
</div>
)
}
Tag.js
import React from 'react'
import styles from './Tag.module.css'
import Link from 'next/link'
import Anime from "react-anime";
export default function Tag({ title, link, delay }) {
return (
<Anime
opacity={[0,1]}
translateY={[50,0]}
duration={3000}
delay={delay}
>
<Link href={link}>
<div className={styles.tag}>
<p className={styles.text}>{title}</p>
</div>
</Link>
</Anime>
)
}
I made an example for using LocalStorage and handle animation with them
export default function App() {
const animated = !!localStorage.getItem("animated");
if (animated === false) {
localStorage.setItem("animated", true);
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{!animated && (
<Anime
opacity={[0, 1]}
translateX={[-50, 0]}
duration={3000}
delay={500}
>
<p>Go to:</p>
</Anime>
)}
{animated && <p>Go to:</p>}
</div>
);
}
also you can test it here

How can I use nested routes with props for a child component

I'm building an react app where I have a feed component and the feed component consists of array of post components. The post component contains a link in it for viewing the full post component. I'm not able to pass the respective props to the full post component. I'm not able to do a nested route for the fullpost component.
this is my layout component
import React, { Component } from "react";
import Header from "../Header/Header";
import classes from "./Layout.css";
import { Route, Switch } from "react-router-dom";
import FullPost from "../Feed/FullPost/FullPost";
import axios from "axios";
import Feed from "../Feed/Feed";
class Layout extends Component {
state = {
users: [],
};
componentDidMount() {
axios
.get("https://goodwill-60d8a.firebaseio.com/Users.json")
.then((response) => {
this.setState({ users: response.data });
});
}
render() {
console.log(this.state.users);
return (
<div className={classes.main}>
<div>
<Header />
</div>
<div className={classes.content}>
<Switch>
<Route
path="/"
exact
render={() => <Feed users={this.state.users} />}
/>
<Route path="/fullpost" exact render={() => <FullPost />} />
</Switch>
</div>
</div>
);
}
}
export default Layout;
FEED component
import React from "react";
import Post from "./Post/Post";
import classes from "./Feed.css";
const feed = (props) => {
const feedItems = Object.keys(props.users).map((key) => ({
id: key,
...props.users[key],
}));
return (
<div className={classes.feed}>
{feedItems.map((items) => (
<Post
key={items.id}
profilename={items.profileName}
profilepic={items.profilePic}
timestamp={items.timeStamp}
contentimage={items.contentImage}
contenttext={items.contentText}
trend={items.trend}
></Post>
))}
</div>
);
};
export default feed;
Post component
import React from "react";
import classes from "./Post.css";
import ShareButton from "../../UI/ShareButton/ShareButton";
import { Link } from "react-router-dom";
const post = (props) => {
return (
<div className={classes.post}>
<div className={classes.header}>
<div className={classes.profileimage}>
<img className={classes.pic} src={props.profilepic} alt="" />
</div>
<div className={classes.name}>{props.profilename}</div>
<div className={classes.timestamp}>{props.timestamp}</div>
</div>
<div className={classes.container}>
<div className={classes.image}>
<img src={props.contentimage} alt="" />
</div>
<div>
<div className={classes.text}>
<span>{props.contenttext}</span>
</div>
<div className={classes.fullpost}>
<Link to="/fullpost" {...props}>
See Full Post
</Link>
</div>
</div>
</div>
<div className={classes.footer}>
<div className={classes.trend}>
<span>{props.trend}</span>
</div>
<ShareButton />
</div>
</div>
);
};
export default post;
Full Post component
import React from "react";
import classes from "./FullPost.css";
import pic from "../../../Assets/Images/self.jpg";
import { Link } from "react-router-dom";
const fullPost = (props) => {
return (
<div className={classes.fullpost_container}>
<div className={classes.photo_container}>
<img src={props.profilepic} alt=" " />
</div>
<div className={classes.sidebar}>
<div className={classes.profileimage}>
<img src={props.profilePic} alt="" />
</div>
<div className={classes.profilename}>Tony Kroos</div>
<div className={classes.timestamp}>3 Hours Ago</div>
</div>
<div className={classes.feedlink}>
<Link to="/" className={classes.feedlink_text}>
See more posts
</Link>
</div>
</div>
);
};
export default fullPost;

React Router v4 not loading component

For some reason, my web app is not directing to the component whenever I go to the parameters. Specifically, it is not going to the Battle component.
Here is what the navigation looks:
import React from 'react';
import Header from './components/Header/Header';
import SelectPlayers from './pages/SelectPlayers/SelectPlayers';
import Popular from './pages/Popular/Popular'
import Battle from './pages/Battle/Battle'
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
function App() {
return (
<Router>
<div className={'flex flex-column'}>
<Header />
<Switch>
<Route exact path={'/'} component={Popular}/>
<Route exact path={'/battle/select-player'} component={SelectPlayers} />
<Route exact path={'/results?playerOne=:playerOne&playerTwo=:playerTwo'} component={Battle} />
</Switch>
</div>
</Router>
);
}
export default App;
In the SelectPlayers component, whenever the user presses a button it runs:
import React, {useState} from 'react';
function SelectPlayers(props) {
const [playerOne, setPlayerOne] = useState('');
const [playerTwo, setPlayerTwo] = useState('');
function setPlayerName(event, player){
if (player === 1){
setPlayerOne(event.target.value)
} else if (player === 2) {
setPlayerTwo(event.target.value)
}
}
function goToBattle(event){
event.preventDefault();
props.history.push(`/results?playerOne=${playerOne}&playerTwo=${playerTwo}`)
}
return (
<div className={'pa3 mh7-l mh7-m'}>
<div className="flex flex-column">
<div className={'mb1'}>
<h1 className={'mb0'}>Player One</h1>
<input onChange={(e) => setPlayerName(e, 1)} type="text" placeholder={'github username'} className={'input-reset pa1 w-100 h2 ba b--black br2'}/>
</div>
<div className="tc dark-red">
<h1>Versus</h1>
</div>
<div className={'mb3'}>
<h1 className={'mb0 mt0 tr'}>Player Two</h1>
<input onChange={(e) => setPlayerName(e, 2)} type="text" placeholder={'github username'} className={'input-reset pa1 w-100 h2 ba b--black br2'}/>
</div>
<div>
<button onClick={(e) => goToBattle(e)} className={'input-reset pa1 h2 fw1 bg-black white ba w-100 b--black br2'}>Battle</button>
</div>
</div>
</div>
);
}
export default SelectPlayers;
On the Battle component, I write some console.log stuff just to check if the Component loaded. However, whenever I go to that parameter, none of the code in my componentDidMount is running. I don't see any of the console.logs I wrote in componentDidMount in my developer console. Here is the component:
import React, {Component} from 'react';
class Battle extends Component {
constructor(props){
super(props)
}
componentDidMount() {
console.log('runngins');
console.log(this.props);
}
render() {
return (
<div className={'pa3 mh7-l mh7-m'}>
<div className="flex flex-column">
</div>
</div>
);
}
}
export default Battle;
You can see the code at this repo: https://github.com/tarekgabarin/github_compete
It would be greatly appreciated if anyone helped me.
As per your new comment that code is working without queryset, looks like there is some problem with your queryset parameters.
As suggested in comment box, don't define Router with queryset.
<Switch>
<Route exact path={'/'} component={Popular}/>
<Route exact path={'/battle/select-player'} component={SelectPlayers} />
<Route exact path={'/results'} component={Battle} />
</Switch>
In your SelectPlayers component, navigate to next page with queryset.
props.history.push("/results?playerOne=" +playerOne+ "&playerTwo=" +playerTwo)
On Battle component, use (query-string) to read the parameter. For example:
const values = queryString.parse(this.props.location.search);
const player_one = values.playerOne
const player_two = values.playerTwo
Please note that my above code is not tested.
Thanks

Categories