unable to select another option after selection with react select - reactjs

Updated code: Im trying to first display carsList and only when selectedMake is selected, I would update the state with the result from filter and show another array. I tried storing carsList in updatedCarsList so it has all the cars on page load but Im missing something here.
CarOffers.jsx
const CarOffers = () => {
const [carsList, setCarsList] = useState([]);
const [updatedCarsList, setUpdatedCarsList] = useState([]);
const [selectedMake, setSelectedMake] = useState(undefined);
const getCars = () => {
axios.get(url)
.then((response) => {
return setCarsList(response.data)
})
}
const handleMakeChange = (select) => {
setSelectedMake(select.value)
}
const applyFilters = () => {
let updatedCarsList = carsList
if(selectedMake) {
updatedCarsList = carsList.filter(car => car.make === selectedMake)
setUpdatedCarsList(updatedCarsList);
} else {
setUpdatedCarsList(carsList)
}
}
useEffect(() => {
getCars()
applyFilters()
}, [ selectedMake ]);
return (
<div className="mka__wrapper-car-offers">
<div className="mka__container">
<div className="mka__content-car-offers">
<div className="mka__content-grid-offers">
<div className="item1">
< CarSlider/>
<div className="mka-responsive-item">
< DisplayCars/>
< SortingCars/>
< CarAlignment/>
</div>
</div>
<div className="item2">
<div className="mka__side-bar-divider">
< Search
carsList={carsList}/>
</div>
<div>
< FilterSideBar
carsList={carsList}
handleMakeChange={handleMakeChange} />
</div>
</div>
<div className="item3">
<Cars updatedCarsList={updatedCarsList}/>
</div>
</div>
</div>
</div>
</div>
)
}
export default CarOffers;
Cars.jsx
const Cars = ({ updatedCarsList }) => {
return (
<div className='mka__cars-grid'>
{updatedCarsList.map(car =>
<CarsItem key={car.id} car={car}/>)}
</div>
)
}
export default Cars
CarItem.jsx
const CarsItem = ({car: {year,month,transmission,mileage,price,title,link}}) => {
return (
<Fragment>
<div className="cars-item_wrapper">
<div className="cars-item_image">
<img src={link} alt="car" />
</div>
<div>
<a
className="cars-item_car-title"
href="/"
>
{title}
</a>
</div>
<div className=" cars-item_separator"></div>
<p className="cars-item_car-text">{price}</p>
</div>
</Fragment>
)
}
export default CarsItem

Move your applyFilters above getCars
Does Select need to be in <>
distinctBy... urgh.. use Set const unique = [...new Set(data.map(item => item.value))]
applyFilters... axios is async, but your setting a value so state doesn't update so no re-render? Maybe.
selectedMake - don't use null as a default, use undefined.
Hope that helps, feels like a state management issue.
... think its this ....
You are using carsList as your list of cars, however you are setting the value of carsList with setCarsList(updatedCarsList)... updatedCarsList is a filtered list of cars... only car => car.make === selectedMake so once you've selected a make your carList is only cars with the selected make.
Solution is to
Either separate the list from the filtered list
or preferably keep list, but pass the filtered state to the component that needs it... but not update state of the original list by calling setCarsList(updatedCarsList);
if (selectedMake){
updatedCarsList = updatedCarsList.filter(
car => car.make === selectedMake
)
};
setCarsList(updatedCarsList);

Related

How i can refresh this function on started value

Hi! i have a problem with my state in React, I have two onMouse functions, the first one is to add an element and the second one is to delete, unfortunately the second one does not delete and the added element 'opacity' is rendered.
let menuItems = ['Tasks', 'Issues', 'Files', 'Raports']
const [item, setItem] = useState(menuItems)
const handleSpace = (id) => {
menuItems.splice(id, 0, 'opacity')
setItem([...item])
}
const restart = () => {
menuItems = ['Tasks', 'Issues', 'Files', 'Raports']
setItem([...item])
}
return (
<>
<div className="dashboard" style={slide.flag ? {left: '-105%'} : {left: '0%'}}>
<div className="dashboard__nav">
<ul className="dashboard__nav-list">
{item.map((item, id) => {
return <li className="dashboard__nav-item" key={id} onMouseOver={() => handleSpace(id)} onMouseLeave={restart}>{item}</li>
})}
</ul>
</div>
<div className="dashboard__array">
{tasks.map((task, id) => {
return (
<div className="dashboard__array-item" key={id}>
<div className="dashboard__array-item-header">
<p className="dashboard__array-item-header-title">{task}</p>
<button className="dashboard__array-item-header-cancel">
<FontAwesomeIcon icon={faCancel} />
</button>
</div>
<div className="dashboard__array-item-main">
<p className="dashboard__array-item-main-description">{descriptionTasks[id]}</p>
<p className="dashboard__array-item-main-button">Show More</p>
</div>
</div>
)
})}
</div>
</div>
</>
)
I already created setItem(menuItems), it removed the element 'opacity, but juz it didn't add it a second time
It seems that the two functions might be over complicating the handling of the item state.
Try handle setItem without changing another variable menuItems, so it can be used as a reset value at anytime.
Example:
const menuItems = ["Tasks", "Issues", "Files", "Raports"];
const [item, setItem] = useState(menuItems);
const handleSpace = (id) =>
setItem((prev) => {
const newItems = [...prev];
newItems.splice(id, 0, "opacity");
return newItems;
});
const restart = () => setItem(menuItems);
Hope this will help.

How can I do in React so that once a product is added to the cart if that product has already been added before it does not repeat a new object?

[ I need to avoid the duplication of an object that has already been added to the cart, so that once I add it again, I only add the quantity property of the previous object, which would be the same ]
[CartContext.js]
import React, { createContext, useState } from "react";
export const CarritoContext = createContext();
export default function CartContext({ children }) {
const [addToCarrito, setAddToCarrito] = useState([]);
[This is the function that I cannot modify so that it complies with a certain rule of not adding duplicates of an object that has already been added to the cart, only increasing its quantity of the already added object]
function addItem(item, quantity) {
setAddToCarrito(
addToCarrito.filter((elemento, pos) => {
if (elemento.item.id === item.id) {
addToCarrito[pos].quantity += quantity;
return false;
}
return true;
})
);
if (quantity === 0) {
setAddToCarrito([...addToCarrito]);
} else {
setAddToCarrito([...addToCarrito, { item, quantity }]);
}
}
function clear() {
setAddToCarrito([]);
}
function removeItem(itemId) {
const newItems = addToCarrito.filter((item) => item.item.id !== itemId);
setAddToCarrito(newItems);
}
console.log(addToCarrito);
return (
<>
<CarritoContext.Provider
value={{ addToCarrito, setAddToCarrito, clear, addItem, removeItem }}
>
{children}
</CarritoContext.Provider>
</>
);
}
[ItemAside.js]
import React, { useState, useContext } from "react";
import { Link } from "react-router-dom";
import ItemCount from "../ItemCount/ItemCount";
import { CarritoContext } from "../../context/CartContext";
const ItemAside = ({ jackets }) => {
const [quantityCarro, setQuantityCarro] = useState(0);
const [branded] = useState(jackets.brand);
let { addToCarrito } = useContext(CarritoContext);
let { setAddToCarrito } = useContext(CarritoContext);
let { clear } = useContext(CarritoContext);
let { addItem } = useContext(CarritoContext);
let { removeItem } = useContext(CarritoContext);
const onAdd = (cantidadCarro) => {
setQuantityCarro(cantidadCarro);
setAddToCarrito([
...addToCarrito,
{ item: jackets, quantity: cantidadCarro }
]);
addItem(jackets, cantidadCarro);
};
return (
<div className="container-vertical">
<aside style={{ width: "100%" }}>
<div className="container-cuadrado">
<div>
<h3>${jackets.price}</h3>
</div>
<div>
<p>and FREE Returns</p>
</div>
<div>
<p>
Delivery for <strong>$39.99</strong>
</p>
<p>
between <strong>17 - 30 April</strong>
</p>
</div>
<div>
<small>
<span className="ubicacion"></span> Deliver to Argentina
</small>
</div>
<div>
{quantityCarro ? (
<>
<Link to="/cart">
<button className="close zbutton">Buy now</button>
</Link>
<p onClick={clear}>Limpiar carro </p>
<br />
<br />
<p onClick={() => removeItem(jackets.id)}>
{`Quitar ${jackets.name} de el carro`}
</p>
</>
) : (
<ItemCount
stock={jackets.stock}
branded={branded}
initial={0}
onAdd={onAdd}
/>
)}
</div>
<div>
<div className="celwidget">
<div className="a-section a-spacing-small a-text-left celwidget">
<span className="a-declarative">
<span className="aok-align-center">
<img
alt=""
src="https://images-na.ssl-images-amazon.com/images/G/30/x-locale/checkout/truespc/secured-ssl._CB485936936_.png"
height="15px"
/>
</span>
<span className="a-letter-space"></span>
<span
className="dataspan"
style={{
cursor: "pointer",
color: "#0099C0",
}}
data-hover="We work hard to protect your security and privacy. Our payment security system encrypts your information during transmission. We don’t share your credit card details with third-party sellers, and we don’t sell your information to others."
>
Secure transaction
</span>
</span>
</div>
</div>
</div>
<div className="info-shipping">
<div>
<p>Shipping from</p>
<p>Sold by</p>
</div>
<div>
<p>Carvel</p>
<p>Carvel</p>
</div>
</div>
<div className="gift-container">
<label className="control control--checkbox">
<input type="checkbox" className="checkgift" />
<small className="small-gift">
Add a gift ticket to facilitate returns
</small>
</label>
</div>
</div>
</aside>
</div>
);
};
export default ItemAside;
I think filter is not the correct function to use. Filter needs to filter object. You are trying to mutate them as well inside. The filter function is immutable which means that it generates a new array instead of an old one.
addToCarrito.filter((elemento, pos) => {
if (elemento.item.id === item.id) {
addToCarrito[pos].quantity += quantity; // <- mutating prev value(bad)
return false;
}
return true;
})
For this task is better to use an object, rather than an array. That will simplify a lot your code.
const [products, setProducts] = useState({})
const addProduct = (item, quantity) => {
// if product already in the object - take it, otherwise add new with 0 quatity
const newProduct = { ...(product[item.id] ?? {...item, quantity: 0}) }
newProduct.quantity += 1
setProducts(products => ({
…products,
[item.id]: newProduct
})
})
}
// here the array of your products, f.e. for iteration
const productList = React.useMemo(() => Object.values(products), [products])

Use State not updating as expected

Fairly new to react and trying to build a clone of The Movie Database site. I want this toggle switch to change my api call from movies to tv. It starts working after a couple clicks, but then it throws everything off and it's not displaying the correct items anyway. Not really sure what's going on here...or even why it starts working after two clicks. Anyone know whats up with this?
import React, { useState, useEffect } from "react";
import axios from "axios";
import API_KEY from "../../config";
const Popular = ({ imageUri }) => {
// GET POPULAR MOVIES
const [popularMovies, setPopularMovies] = useState("");
const [genre, setGenre] = useState("movie");
console.log(genre);
const getPopular = async () => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${genre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, []);
const listOptions = document.querySelectorAll(".switch--option");
const background = document.querySelector(".background");
const changeOption = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
getPopular();
listOptions.forEach((option) => {
option.classList.remove("selected");
});
el = el.target.parentElement.parentElement;
let getStartingLeft = Math.floor(
listOptions[0].getBoundingClientRect().left
);
let getLeft = Math.floor(el.getBoundingClientRect().left);
let getWidth = Math.floor(el.getBoundingClientRect().width);
let leftPos = getLeft - getStartingLeft;
background.setAttribute(
"style",
`left: ${leftPos}px; width: ${getWidth}px`
);
el.classList.add("selected");
};
return (
<section className="container movie-list">
<div className="flex">
<div className="movie-list__header">
<h3>What's Popular</h3>
</div>
<div className="switch flex">
<div className="switch--option selected">
<h3>
<a
data-genre="movie"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
In Theaters
</a>
</h3>
<div className="background"></div>
</div>
<div className="switch--option">
<h3>
<a
data-genre="tv"
onClick={(e) => changeOption(e)}
className="switch--anchor"
>
On TV
</a>
</h3>
</div>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies &&
popularMovies.map((movie, idX) => (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + "w500" + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
))}
</div>
</div>
</div>
</section>
);
};
export default Popular;
You're using the array index as your key prop when you're mapping your array.
You should use an id that is specific to the data that you're rendering.
React uses the key prop to know which items have changed since the last render.
In your case you should use the movie id in your key prop instead of the array index.
popularMovies.map((movie) => (
<div key={movie.id} className="card">
<div className="image">
<img src={imageUri + 'w500' + movie.poster_path} />
</div>
<p>{movie.title}</p>
</div>
));
Also
You're calling the api directly after setGenre. However state changes aren't immediate. So when you're making your api call you're still sending the last movie genre.
Two ways of fixing this:
You could call your function with the genre directly, and change your function so it handles this case:
getPopular('movie');
Or you could not call the function at all and add genre as a dependency of your useEffect. That way the useEffect will run each time the genre change.
useEffect(() => {
getPopular();
}, [genre]);
PS: You should consider splitting your code into more component and not interacting with the DOM directly.
To give you an idea of what it could look like, I refactored a bit, but more improvements could be made:
const Popular = ({ imageUri }) => {
const [popularMovies, setPopularMovies] = useState('');
const [genre, setGenre] = useState('movie');
const getPopular = async (movieGenre) => {
const response = await axios.get(
`https://api.themoviedb.org/3/discover/${movieGenre}?sort_by=popularity.desc&api_key=${API_KEY}`
);
setPopularMovies(response.data.results);
};
useEffect(() => {
getPopular();
}, [genre]);
const changeHandler = (el) => {
let getGenre = el.target.dataset.genre;
setGenre(getGenre);
};
const isMovieSelected = genre === 'movie';
const isTvSelected = genre === 'tv';
return (
<section className="container movie-list">
<div className="flex">
<MovieHeader>What's Popular</MovieHeader>
<div className="switch flex">
<Toggle onChange={changeHandler} selected={isMovieSelected}>
In Theaters
</Toggle>
<Toggle onChange={changeHandler} selected={isTvSelected}>
On TV
</Toggle>
</div>
</div>
<div className="scroller">
<div className="flex flex--justify-center">
<div className="flex flex--nowrap container u-overScroll">
{popularMovies.map((movie) => {
const { title, id, poster_path } = movie;
return (
<MovieItem
title={title}
imageUri={imageUri}
key={id}
poster_path={poster_path}
/>
);
})}
</div>
</div>
</div>
</section>
);
};
export default Popular;
const Toggle = (props) => {
const { children, onChange, selected } = props;
const className = selected ? 'switch--option selected' : 'switch--option';
return (
<div className={className}>
<h3>
<a
data-genre="movie"
onClick={onChange}
className="switch--anchor"
>
{children}
</a>
</h3>
<div className="background"></div>
</div>
);
};
const MovieHeader = (props) => {
const { children } = props;
return (
<div className="movie-list__header">
<h3>{children}</h3>
</div>
);
};
const MovieItem = (props) => {
const { title, imageUri, poster_path } = props;
return (
<div key={idX} className="card">
<div className="image">
<img src={imageUri + 'w500' + poster_path} />
</div>
<p>{title}</p>
</div>
);
};

React - Warning: Each child in a list should have a unique "key" prop

In this simple React App, I don't understand why I get the following warning message:
Warning: Each child in a list should have a unique "key" prop.
To me it seems that I put the key at the right place, in form of key={item.login.uuid}
How can I get rid of the warning message?
Where would be the right place to put the key?
App.js
import UserList from './List'
const App = props => {
const [id, newID] = useState(null)
return (
<>
<UserList id={id} setID={newID} />
</>
)
}
export default App
List.js
const UserList = ({ id, setID }) => {
const [resources, setResources] = useState([])
const fetchResource = async () => {
const response = await axios.get(
'https://api.randomuser.me'
)
setResources(response.data.results)
}
useEffect(() => {
fetchResource()
}, [])
const renderItem = (item, newID) => {
return (
<>
{newID ? (
// User view
<div key={item.login.uuid}>
<div>
<h2>
{item.name.first} {item.name.last}
</h2>
<p>
{item.phone}
<br />
{item.email}
</p>
<button onClick={() => setID(null)}>
Back to the list
</button>
</div>
</div>
) : (
// List view
<li key={item.login.uuid}>
<div>
<h2>
{item.name.first} {item.name.last}
</h2>
<button onClick={() => setID(item.login.uuid)}>
Details
</button>
</div>
</li>
)}
</>
)
}
const user = resources.find(user => user.login.uuid === id)
if (user) {
// User view
return <div>{renderItem(user, true)}</div>
} else {
// List view
return (
<ul>
{resources.map(user => renderItem(user, false))}
</ul>
)
}
}
export default UserList
The key needs to be on the root-level element within the loop. In your case, that's the fragment (<>).
To be able to do that, you'll need to write it out fully:
const renderItem = (item, newID) => {
return (
<Fragment key={item.login.uuid}>
{newID ? (
...
)}
</Fragment>
);
}
(You can add Fragment to your other imports from react).
Note that the fragment isn't actually needed in your example, you could drop it and keep the keys where they are since then the <div> and <li> would be the root element:
const renderItem = (item, newId) => {
return newID ? (
<div key={item.login.uuid}>
...
</div>
) : (
<li key={item.login.uuid}>
...
</li>
)
}
What if you create 2 separate components, one for the user view and one for the list item. That way you only need to pass the user prop. Also, use JSX and pass wht key from there.
const UserList = ({ id, setID }) => {
const [resources, setResources] = useState([])
const fetchResource = async () => {
const response = await axios.get(
'https://api.randomuser.me'
)
setResources(response.data.results)
}
useEffect(() => {
fetchResource()
}, [])
const User = ({user}) => (
<div key={user.login.uuid}>
<div>
<h2>
{user.name.first} {user.name.last}
</h2>
<p>
{user.phone}
<br />
{user.email}
</p>
<button onClick={() => setID(null)}>
Back to the list
</button>
</div>
</div>
)
const ListItem = ({user}) => (
<li key={user.login.uuid}>
<div>
<h2>
{user.name.first} {user.name.last}
</h2>
<button onClick={() => setID(user.login.uuid)}>
Details
</button>
</div>
</li>
)
const user = resources.find(user => user.login.uuid === id)
if (user) {
// User view
return <User user={user}</div>
} else {
// List view
return (
<ul>
{resources.map((user, index) => <ListItem key={index} user={user} />)}
</ul>
)
}
}
export default UserList

pagination using react, react-router, and redux [duplicate]

I have a react app which is the front end for a shopping site.
I have a products page and I am trying to add pagination from react-js-pagination to the bottom of it so that I do not have to render the entire list of products at once.
I have followed the guidlines on implementing the pagination from https://www.npmjs.com/package/react-js-pagination but I still cannot get it to display (the rest of the page displays properly).
Can anybody see why?
Please see my code for the entire page below:
import React from 'react';
import Pagination from 'react-js-pagination';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import changeBrandFilter from '../actions/changeBrandFilter';
import changePriceFilter from '../actions/changePriceFilter';
import CategoryOverview from './CategoryOverview';
import Filter from './Filter';
import ProductsListItem from './ProductsListItem';
import ProductsPageContainerCSS from './ProductsPageContainer.css';
class ProductsPage extends React.Component{
createCategoryOverview() {
return this.props.overview.map(overview => {
return (
<CategoryOverview
title={overview.title}
text={overview.text}
image={overview.imageSource}
alt={overview.imageAlt}
/>
)
})
}
createBrandFilterList() {
return this.props.brandFilters.map(filter => {
return (
<Filter
key={filter.brand}
id={filter.brand}
changeFilter={() => this.props.changeBrandFilter(filter)}
inuse={filter.inuse}
disabled={filter.disabled}
/>
)
})
}
createPriceRangeFilterList() {
return this.props.priceRangeFilters.map(filter => {
return (
<Filter
key={filter.priceRange}
id={filter.priceRange}
changeFilter={() => this.props.changePriceFilter(filter)}
inuse={filter.inuse}
disabled={filter.disabled}
/>
)
})
}
filterDivExtenionToggle () {
var filterDivExtension = document.querySelector('.filterDivExtension');
var chevronUp = document.querySelector('#chevronUp');
var chevronDown = document.querySelector('#chevronDown');
var icon;
if (filterDivExtension.style.display === 'block') {
filterDivExtension.style.display = 'none';
chevronUp.style.display = 'none';
chevronDown.style.display = 'block';
} else {
filterDivExtension.style.display = 'block';
chevronUp.style.display = 'block';
chevronDown.style.display = 'none';
}
}
createProductsList() {
if(this.props.products.length > 0) {
return this.props.products.map(product =>{
if (this.props.products.indexOf(product) >= this.state.activePage -1 && this.props.products.indexOf(product) < (this.state.activePage*12)) {
return (
<ProductsListItem
key={product.id}
brand={product.brand}
model={product.model}
price={product.price}
image={product.image}
link={"/"+this.props.match.params.type+"/"+product.id}
/>
)
}
})} else {
return <div>No products match the filter criteria selected above.</div>
}
}
constructor(props) {
super(props);
this.state = {activePage: 1};
}
handlePageChange(pageNumber) {
this.setState({activePage: pageNumber});
}
render () {
return (
<div>
<div className="container">
{this.createCategoryOverview()}
<div ClassName="row">
<div className= "filterDiv col-12">
<div className="iconCrossbar">
<i id="chevronDown" className="fa fa-chevron-down" onClick={this.filterDivExtenionToggle}></i>
<i id="chevronUp" className="fa fa-chevron-up" onClick={this.filterDivExtenionToggle}></i>
</div>
<div className="filterDivExtension">
<div className="row">
<div className="filtersList col-md-6 col-12">
Filter by Brand:
<div>
{this.createBrandFilterList()}
</div>
</div>
<div className="filtersList col-md-6 col-12">
Filter by Price Range:
<div>
{this.createPriceRangeFilterList()}
</div>
</div>
</div>
</div>
</div>
</div>
<div className="row productsList">
{this.createProductsList()}
</div>
</div>
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={12}
totalItemsCount={this.props.products.length}
pageRangeDisplayed={2}
onChange={this.handlePageChange}
/>
</div>
)
}
};
function mapStateToProps(state , ownProps) {
let brandFilters = state.brandFilters;
let filtered_brandFilters = brandFilters;
filtered_brandFilters = filtered_brandFilters.filter(
filter => filter.type === ownProps.match.params.type
)
let priceRangeFilters = state.priceRangeFilters;
let filtered_priceRangeFilters = priceRangeFilters;
filtered_priceRangeFilters = filtered_priceRangeFilters.filter(
filter => filter.type === ownProps.match.params.type
)
let products = state.products;
let overviews = state.overviews;
let overview = overviews.filter(
overview => overview.type === ownProps.match.params.type
)
let filtered_products = products;
filtered_products = filtered_products.filter(
product => product.type === ownProps.match.params.type //gets type from the the route params and finds products which have type that matches
)
let activeBrandFilters = brandFilters.filter(
item => item.inuse === true
);
activeBrandFilters.forEach(filter => {
filtered_products = filtered_products.filter(
product => product.brand === filter.brand
)
});
let activePriceRangeFilters = priceRangeFilters.filter(
item => item.inuse === true
);
activePriceRangeFilters.forEach(filter => {
filtered_products = filtered_products.filter(
product => product.priceRange === filter.priceRange
);
});
return {
overview: overview,
brandFilters: filtered_brandFilters,
priceRangeFilters: filtered_priceRangeFilters,
products: filtered_products
};
};
function matchDispatchToProps(dispatch){
return bindActionCreators({changeBrandFilter: changeBrandFilter, changePriceFilter: changePriceFilter}, dispatch);
};
export const ProductsPageContainer = connect(mapStateToProps, matchDispatchToProps)(ProductsPage);
Any help would be greatly appreciated.
Thanks.
Well, I can't help you with react-js-pagination, on the other hand, I did it very easily using react-prime. Paginator React Prime. Ok, so, I'll try to explain it to you,
first thing is to understand what this framework gives to us:
you import it:
import {Paginator} from 'primereact/components/paginator/Paginator';
then probably, you will have a list of components you have to render in order to paginate through it.
On your container component you have to set these values in order for you paginator to work:
constructor() {
super();
this.state = {first: 0, rows: 10};
this.onPageChange = this.onPageChange.bind(this);
}
onPageChange(event) {
this.setState({
first: event.first,
rows: event.rows
});
}
then you will have the paginator component itself:
<Paginator first={this.state.first} rows={this.state.rows} totalRecords={yourcomponentlist.length} onPageChange={this.onPageChange}></Paginator>
Now let's analyse it, we have a number of rows showing up in each page (rows), and the relative number of the first line to be displayed(first). so, you can have your list of components working with paginator using the slice javascript method to render only the components you wish after paginating.
<tbody>
{
this.props.components.slice(this.state.first, this.state.first +
this.state.rows).map((component) => {
return <ComponentListItem key={component._id} {...componentData} />;
})
}
</tbody>
That's it, I hope I was able to help you understand how this paginator works, react-prime is a great toolbelt, it has many themes for your design as well, I was very happy using it!
Ok so if you read my comments on Leonel's answer you will see that I did manage to get the paginator from react-js-paginator to display but could still not get it to work.
I made my own custom basic paginator component instead.
please find the paginator component that i made below:
import React from 'react';
class Paginaton extends React.Component {
render () {
return (
<div className="row">
<div className="pagination">
<button id="prevPage" className="btn" disabled={this.props.disabled1} onClick={() => this.props.onclick1()}>prev</button>
<button id="nextPage" className="btn" disabled={this.props.disabled2} onClick={() => this.props.onclick2()}>next</button>
</div>
</div>
)
}
}
export default Paginaton;
As you can see this is just a prev button and a next button.
I then, in the container component, made sure that only the button which was required to be active was shown as active and the button that was not required to be active was shown as inactive. this made sure that prev was not a clickable option when on the first page of products and next was not a clickable option when on the last page of products.
I also made sure to add a 'key' prop to the component that was unique to the route that the component was displayed on. This was needed because my pagination relies on a state that I have set in the component which declares the 'activePage' so that when I would go on to a page of products of another type (from kits products to tanks products for example), the component would remount (since both routes render the same component, with the products rendered being decided by the route parameters) and the state would revert to its initial state ({activePage: 1}).
Please see the container component below:
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import changeBrandFilter from '../actions/changeBrandFilter';
import changePriceFilter from '../actions/changePriceFilter';
import CategoryOverview from './CategoryOverview';
import Filter from './Filter';
import ProductsListItem from './ProductsListItem';
import ProductsPageContainerCSS from './ProductsPageContainer.css';
import Pagination from './Pagination';
class ProductsPage extends React.Component{
createCategoryOverview() {
let i = 1;
return this.props.overview.map(overview => {
i++
return (
<CategoryOverview
key={"catOverview"+i} //each child in an array or iterator should have a unique "key" prop
title={overview.title}
text={overview.text}
image={overview.imageSource}
alt={overview.imageAlt}
/>
)
})
}
createBrandFilterList() {
let i = 1;
return this.props.brandFilters.map(filter => {
i++
return (
<Filter
key={filter.brand+i+"brand"}
name={this.props.match.params.type + "brandFilter"} //so that each seperate group of radio buttons (filters) refer only to each other. (the name is shared within each group)
id={filter.brand}
changeFilterResetPageNumber={() => {this.props.changeBrandFilter(filter); this.handlePageChange(1)}} //without page reset would often get no products displayed on filter application due to the activePage state remaining at the page that was active at the time of filter application
inuse={filter.inuse}
/>
)
})
}
createPriceRangeFilterList() {
let i = 1;
return this.props.priceRangeFilters.map(filter => {
i++
return (
<Filter
key={filter.priceRange+i+"priceRange"}
name={this.props.match.params.type + "priceFilter"}
id={filter.priceRange}
changeFilterResetPageNumber={() => {this.props.changePriceFilter(filter); this.handlePageChange(1)}}
inuse={filter.inuse}
/>
)
})
}
filterDivExtenionToggle () {
var filterDivExtension = document.querySelector('.filterDivExtension');
var chevronUp = document.querySelector('#chevronUp');
var chevronDown = document.querySelector('#chevronDown');
var icon;
if (filterDivExtension.style.display === 'block') {
filterDivExtension.style.display = 'none';
chevronUp.style.display = 'none';
chevronDown.style.display = 'block';
} else {
filterDivExtension.style.display = 'block';
chevronUp.style.display = 'block';
chevronDown.style.display = 'none';
}
}
createProductsList() {
if(this.props.products.length > 0) {
return this.props.products.map(product =>{
if (this.props.products.indexOf(product) >= (this.state.activePage*12) - 12 && this.props.products.indexOf(product) < (this.state.activePage*12)) { //render the 12 (number of products per page) products that correspond to the current (active) page
return (
<ProductsListItem
key={product.id}
brand={product.brand}
model={product.model}
price={product.price}
image={product.image}
link={"/"+this.props.match.params.type+"/"+product.id}
/>
)
}
})} else {
return <div>No products match the filter criteria selected above.</div>
}
}
state = {
activePage: 1
}
handlePageChange(pageNumber) {
this.setState({activePage: pageNumber});
}
createPagination() {
if (this.props.products.length > 12) {
if (this.props.products.length > this.state.activePage * 12 && this.state.activePage > 1) { //if there are products following AND preceding the current page
return (
<Pagination
onclick1={() => this.handlePageChange(this.state.activePage - 1)}
onclick2={() => this.handlePageChange(this.state.activePage + 1)}
disabled1={false}
disabled2={false}
/>
)
} else if (this.props.products.length > this.state.activePage * 12) { //if there are only products following the current page
return (
<Pagination
onclick1={() => this.handlePageChange(this.state.activePage - 1)}
onclick2={() => this.handlePageChange(this.state.activePage + 1)}
disabled1={true}
disabled2={false}
/>
)
} else if (this.state.activePage > 1) { //if there are only products preceding the current page
return (
<Pagination
onclick1={() => this.handlePageChange(this.state.activePage - 1)}
onclick2={() => this.handlePageChange(this.state.activePage + 1)}
disabled1={false}
disabled2={true}
/>
)
}
}
}
render () {
return (
<div>
<div className="container">
{this.createCategoryOverview()}
<div className="row">
<div className= "filterDiv col-12">
<div className="iconCrossbar">
<i id="chevronDown" className="fa fa-chevron-down" onClick={this.filterDivExtenionToggle}></i>
<i id="chevronUp" className="fa fa-chevron-up" onClick={this.filterDivExtenionToggle}></i>
</div>
<div className="filterDivExtension">
<div className="row">
<div className="filtersList col-md-6 col-12">
Filter by Brand:
<div>
{this.createBrandFilterList()}
</div>
</div>
<div className="filtersList col-md-6 col-12">
Filter by Price Range:
<div>
{this.createPriceRangeFilterList()}
</div>
</div>
</div>
</div>
</div>
</div>
<div className="row productsList">
{this.createProductsList()}
</div>
{this.createPagination()}
</div>
</div>
)
}
};
function mapStateToProps(state , ownProps) {
let brandFilters = state.brandFilters;
let filtered_brandFilters = brandFilters;
filtered_brandFilters = filtered_brandFilters.filter(
filter => filter.type === ownProps.match.params.type //gets type from the the route params and finds products which have type that matches
)
let priceRangeFilters = state.priceRangeFilters;
let filtered_priceRangeFilters = priceRangeFilters;
filtered_priceRangeFilters = filtered_priceRangeFilters.filter(
filter => filter.type === ownProps.match.params.type
)
let overviews = state.overviews;
let overview = overviews.filter(
overview => overview.type === ownProps.match.params.type
)
let products = state.products;
let filtered_products = products;
filtered_products = filtered_products.filter(
product => product.type === ownProps.match.params.type
)
let activeBrandFilters = filtered_brandFilters.filter(
item => item.inuse === true
);
activeBrandFilters.forEach(filter => {
if (filter.brand != "ALL") {
filtered_products = filtered_products.filter(
product => product.brand === filter.brand
)
}
});
let activePriceRangeFilters = filtered_priceRangeFilters.filter(
item => item.inuse === true
);
activePriceRangeFilters.forEach(filter => {
if (filter.priceRange != "ALL") {
filtered_products = filtered_products.filter(
product => product.priceRange === filter.priceRange
);
}
});
let key = ownProps.match.params.type;
return {
overview: overview,
brandFilters: filtered_brandFilters,
priceRangeFilters: filtered_priceRangeFilters,
products: filtered_products,
key: key //a change of key property means the component remounts. this was needed so that when on a second page of products (state is activePage: 2) and switching to a 'page' with products type that does not have a second page (uses same components but displays different type of products), no products would be displayed because the component did not remount and thh state remained the same (activePage did not reset to 1)
};
};
function mapDispatchToProps(dispatch){
return bindActionCreators({changeBrandFilter: changeBrandFilter, changePriceFilter: changePriceFilter}, dispatch);
};
export const ProductsPageContainer = connect(mapStateToProps, mapDispatchToProps)(ProductsPage);

Resources