reactjs pagination showing undesired element when selecting backwards - reactjs

I have created a pagination form in my reactjs app but I am having some problems.
The form should work in that way that if I have around 20 elements the array which displays the elements should be like "1, 2, 3, ... ,18 ,19, 20", and if the current selected element is 10, the array should be like" 1,2,3, ..., 9,10,11,...,18,19,20".
The problem is that when I go and select the elements forward from 1 to n, it works all good, but when I go backwards from 20 to 1 it just keeps creating the "..." element multiple times. Even stranger is that when I console.log the array, the elements look as they should, but the ... html element is still there!
Below are the pictures of the results I have now.
The result I get when I select the elements from n to 1 (the wrong result)
The result I get when I select elements from 1 to n (the desired result)
What I want to do is when I select backwards the 4th element, I want to have the elements "1, 2, 3, 4, 5, ..., 14, 15, 16" but I still get the "..." element appeared unnecessarily.
My code:
var pagearray=[]
if(nPages>10)
{
pagearray.push(1);
pagearray.push(2);
if(currentPage == 3)
{
pagearray.push(3);
pagearray.push(4);
pagearray.push("...");
}
if(currentPage==4)
{
pagearray.push(4);
pagearray.push(5);
pagearray.push("...");
}
if(currentPage == 5)
{
pagearray.push(4);
pagearray.push(5);
pagearray.push(6);
pagearray.push("...");
console.log("1");
}
if(currentPage > 5 && currentPage<parseInt(pageNumbers[pageNumbers.length-5]))
{
pagearray.push("...");
pagearray.push(currentPage-1);
pagearray.push(currentPage);
pagearray.push(currentPage+1);
pagearray.push("...");
}
setPageArray(pagearray);
And then in the end I use .map function to iterate and display all elements in the desired way:
{pageArray1.map(pgNumber => (
<li key={pgNumber}
className= {`page-item ${currentPage == pgNumber && pgNumber != "..." ? 'active' : ''} `} >
<a onClick={() => setCurrentPage(pgNumber)}
className='page-link'
>
{pgNumber}
</a>
</li>
}
Can you please help me and tell me what am I missing here?
Thank you in advance.

It may be because of the key={pgNumber}, because several elements will share the same key ('...'). I would go with key={`${pgNumber}-${index}`} in that case.

Related

Taking 4 random objects from an array of objects and adding some extra properties to it

I want to implement a functionality where I want to take some selected objects totally in a random manner out of an array of objects. And then, add some extra properties to those selected objects by using a spread operator { extra properties, ...selected object}
Algorithm as follows
Taking data as an array of objects (say an array consisting of 150 objects)
Taking 4 random objects out of it based on their Id properties, but no two ids should match (say, it should not be 1, 2, 3, 1 , or 15, 67, 43, 67, they all should be unique , like 45, 67, 89, 12, and so on).
pushing these 4 random objects into the new array, so that I could add the different properites to these 4 objects as per their index positions, inside this array.
finally mapping the modified 4 objects to somewhere else, keeping the rest of (150) objects as it is.
so this is my logic...
const Data = [{
id : 1,
property : 'string1'
},
id : 2,
property : 'string2'
},
id : 3,
property : 'string3'
},
id : 4,
property : 'string4'
},
id : 1,
property : 'string5'
} ... and so on , till data.length;
//
for (let i = 0; i <= 3; i++){
var rand = Data[Math.floor(Math.random() * Data.length)];
console.log(rand); //but this is also giving me 2 duplicate objects, which I need to avoid, so how should I reframe this function?
}
let newArr : any[] = [];
newArr.push(rand); // i want all 4 objects to get stored into this array seperated by a comma, so that I could access them as per their index values
switch(newArr) {
case 0 : {(row : 4, col : 5, ...rand)};
break;
case 1 : {(row : 3, col : 2, ...rand)};
break;
case 2 : {(row : 1, col : 4, ...rand)};
break;
case 3 : {(row : 3, col : 2, ...rand)};\
break;
default :
}
//finally I would like to map these objects into my styled component...
<MyComponent>
Data.map(...)
</MyComponent>
I feel like < I am able to make you understand the solution I want to achieve.
In shortest possible words,
"Out of an array of objects containing 500 objects or even more, I want to select only 4 random objects,
then add few styling properties to those 4 objects using spread operator ..., and then map these 4 objects into <MyComponent />.
All suggestions are welcome and hereby appreciated in advance: )
This is what you need to solve it
let randomsArr: number[] = [];
let newArr : any[] = [];
while(randomsArr.length < 4){
var rand = Data[Math.floor(Math.random() * Data.length)];
if(!randomsArr.find(rnd => rnd == rend)) {
randomsArr.push(rend);
newArr.push(Data[rend]);
}
console.log(rend);
}

Star-rating component logic implementation in react

I am working on a star-rating component in react. I have implemented successfully the full and empty star rating but i got stuck in displaying half stars. I came up with a logic i tried many times but didn't find a way to implement that logic. Currently this component is just displaying star-ratings without any click functionality.
I want to implement this logic:
Suppose we have selectedStars as 2.5 and totalStars as 5 and we want to display two full stars and a half star and the rest empty stars. I separated the selectedStars into two parts one containing the integer part and other containing the floating part. I have successfully separated the two parts using
firstHalf = Math.floor(selectedStars) it will give as a result 2
secondHalf = selectedStars % 1 it will give as a result 0.5
also i have converted totalStars into an array using [...Array(totalStars)] so as to represent five stars in total.
and i am running the loop on indexes.
with the both parts i want to implement this if else ladder which is as follows:
if(index < firstHalf) then use font-awesome "fa fa-star" icon
else if(secondHalf === 0.5) then use font-awesome "fa fa-star-half-o" icon and increment secondHalf i did this because there will be only one half star and next time when it checks for the secondHalf value the condition comes out to be false and it will move to the next statement.
else use font-awesome "fa fa-star-o" icon to represent empty stars.
I hope you understand what i want to implement here.
This is how I implemented your secondMethod in the codesandbox you provided:
secondMethod = () => {
// implement the code for full, empty and half stars here.
const { selectedStars, totalStars } = this.state;
return [...Array(totalStars)].map((el, i) =>
// check if current star should be half
i < selectedStars && i + 1 > selectedStars ?
<i key={i} className="fa fa-star-half-o" />
// not half, so check if current star should be full
: i < selectedStars ? <i key={i} className="fa fa-star" />
// else, current star should be empty
: <i key={i} className="fa fa-star-o" />
);
};

Not allowing items in array to have the same value

On what I'm working right now is a little bit complex for my brain. I've got some data, and that data has a field 'position', and based on that position they are going to be displayed on the client side in that order(for example, for the last item user has added, he can change its position to be 1 and on client side it will be displayed first, then comes rest of the data), and he can always change the position(from 1 to 8, and then it will be displayed the last because that number of data is limited to maximum of 8).
But the problem is when user changes the position for example from 4 to 1, and there already is a data with position 1, so then we have to items with the same position, which should not happen. Is there a solution to go over the array, and check for same values and then replace them?
Example:
There are 2 items, item 1 has position 1 and item 2 has position 2. If we change item 2 position to 1, then both of them will have one, but that item 1 should automatically auto increment to 2.
What I tried so far was do forEach on the array, and check values with conditions but its not working the best. Is there some algorithm to accomplish this?
this.items.forEach((itemRes) => {
let itemDash = result;
if (itemRes.position === result.ordinal) {
if(itemRes.position !== result) {
itemRes.ordinal++;
}
} else if (itemRes.position === this.items.length && itemRes.ordinal >= 8) {
itemRes.position--;
}
})
Here is my code for checking and changing array items and their positions.
Kudos to this gist: https://gist.github.com/albertein/4496103
If I am understanding you correctly, you would want something like presented in the link, so when "TypeScriptifying" it and making it applicable to your (simplified) case:
array = [1, 2, 3, 4, 5];
move(array, element, delta) {
let index = array.indexOf(element);
let newIndex = index + delta;
//Already at the top or bottom.
if (newIndex < 0 || newIndex == array.length) return;
let indexes = [index, newIndex].sort(); //Sort the indexes
//Replace from lowest index, two elements, reverting the order
array.splice(indexes[0], 2, array[indexes[1]], array[indexes[0]]);
}
moveUp(element) {
this.move(this.array, element, -1);
}
moveDown(element) {
this.move(this.array, element, 1);
}
And the corresponding HTML:
<div *ngFor="let a of array">
{{a}}
<button (click)="moveUp(a)">Move Up</button>
<button (click)="moveDown(a)">Move Down</button>
</div>
StackBlitz
This can also give you some inspiration: Move an array element from one array position to another :)

How do I set a class based on a child element's state with Angular?

I am trying to display a results 'table' (built with DIVs as it happens) using Angular. Data looks somethingof it like this:
[['sydney','hotel','2','5','1'],
['sydney','bar','6','5','2'],
['sydney','stand','2','7','3'],
['melbourne','hotel','2','5','1'],
['melbourne','bar','8','0','1']]
What I want firstly is to suppress the repeating city name so that the first row says 'sydney' at the start but the second row and third row don't. Then the fourth says 'melbourne' and the fifth says nothing.
I've achieved this using markup like this:
<div class="row-container"
ng-repeat="row in resultsRows"
<div
ng-repeat="cell in row track by $index"
ng-bind="showValue( cell )">
</div>
</div>
The showValue() function in the controller looks like this:
$scope.currentCityName = '';
function showValue( val ) {
var outValue = '';
if (this.$index === 0) {
if (val === $scope.currentCityName) {
outValue = '';
} else {
$scope.currentCityName = val;
outValue = val;
}
} else {
outValue = val;
}
return outValue;
}
Maybe that's a bit clunky but it works and I get:
sydney hotel 2 5 1
bar 6 5 2
stand 2 7 3
melbourne hotel 2 5 1
bar 8 0 1
Now, though, I want rows that have the city name in them to have a different background colour.
What I think I want is for any 'TR' DIV (I call it that because it contains the left-floated 'TD' DIVs with the data points in them) to check if its first child DIV is not empty (because it has the city name in it) and, if so, to colour its background.
My question is: how do I do that with Angular? Or am I missing another trick..?
How do I get an item in an ng-repeat loop to interrogate a child element?
You are using ng-repeat, which has built-in values like $even and $odd:
$even boolean true if the iterator position $index is even (otherwise false).
$odd boolean true if the iterator position $index is odd (otherwise false).
Use ng-class to give different classed depending on $even and $odd.

Ng-Repeat array to rows and columns

Thanks for taking the time to read this, I was wondering how I might be able to use ng-repeat to create a grid like box of options. I would like to take an array repeat nth number of items and then move to the next row or column until all items are listed. e.g.
assuming I had an array like [opt1,opt2,opt3,opt4,opt5,opt6,opt7] I would like to display it like this:
opt1 opt2 opt3
opt4 opt5 opt6
opt7
This is more a styling/markup problem than an AngularJS one. If you really want to, you can do:
<span ng:repeat="(index, value) in array">
{{value}}<br ng:show="(index+1)%3==0" />
</span>
http://jsfiddle.net/JG3A5/
Sorry for my HAML and Bootstrap3:
.row
.col-lg-4
%div{'ng:repeat' => "item in array.slice(0, array.length / 3)"}
{{item}}
.col-lg-4
%div{'ng:repeat' => "item in array.slice(array.length / 3, array.length * 2/3)"}
{{item}}
.col-lg-4
%div{'ng:repeat' => "item in array.slice(array.length * 2/3, array.length)"}
{{item}}
There is another version, with possibility to use filters:
<div class="row">
<div class="col-md-4" ng-repeat="remainder in [0,1,2]">
<span ng-repeat="item in array" ng-if="$index % 3 == remainder">{{item}}</span>
</div>
</div>
If all of your items are in one single array, your best bet is to make a grid in CSS. This article should be helpful: http://css-tricks.com/dont-overthink-it-grids/
You can use $index from ng-repeat to apply the correct class for your column (in this case a 4 column grid):
<div class="col-{{ $index % 4 }}"></div>
If you have a 2 dimensional array (split into rows and columns) that opens up more possibilities like actually using an HTML table.
I find it easier to simply use ng-repeat combined with ng-if and offsetting any indexes using $index. Mind the jade below:
div(ng-repeat="product in products")
div.row(ng-if="$index % 2 === 0")
div.col(ng-init="p1 = products[$index]")
span p1.Title
div.col(ng-if="products.length > $index + 1", ng-init="p2 = products[$index + 1]")
span p2.Title
div.col(ng-if="products.length <= $index + 1")
Between Performance, Dynamics and Readability
It seems putting the logic in your JavaScript is the best method. I would just bite-the-bullet and look into:
function listToMatrix(list, n) {
var grid = [], i = 0, x = list.length, col, row = -1;
for (var i = 0; i < x; i++) {
col = i % n;
if (col === 0) {
grid[++row] = [];
}
grid[row][col] = list[i];
}
return grid;
}
var matrix = listToMatrix(lists, 3);
console.log('#RedPill', matrix);
# Params: (list, n)
Where list is any array and n is an arbitrary number of columns desired per row
# Return: A matroid
# Note: This function is designed to orient a matroid based upon an arbitrary number of columns with variance in its number of rows. In other words, x = desired-columns, y = n.
You can then create an angular filter to handle this:
Filter:
angular.module('lists', []).filter('matrical', function() {
return function(list, columns) {
return listToMatrix(list, columns);
};
});
Controller:
function listOfListsController($scope) {
$scope.lists = $http.get('/lists');
}
View:
<div class="row" ng-repeat="row in (lists | matrical:3)">
<div class="col col-33" ng-repeat="list in row">{{list.name}}</div>
</div>
With this, you can see you get n number of rows -- each containing "3" columns. When you change the number of desired columns, you'll notice the number of rows changes accordingly (assuming the list-length is always the same ;)).
Here's a fiddle.
Note, that you get the ol' Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!. This is because Angular is recalling the matrical function upon every iteration. Allegedly, you can use the as results alias to prevent Angular from reevaluating the collection, but I had no luck. For this, it may be better to filter the grid inside of your controller and use that value for your repeater: $filter('matrical')(items) -- but please post back if you come across an elegant way of filtering it in the ng-repeat.
I would stress, again, you're probably heading down a dark alley by trying to write the logic in your view -- but I encourage you to try it in your view if you haven't already.
Edit
The use of this algorithm should be combined with a Matrical Data-Structure to provide methods of push, pop, splice, and additional methods -- in tandem with appropriate logic to complement Bi-Directional Data-Binding if desired. In other words, data-binding will not work out of the box (of course) as when a new item is added to your list, a reevaluation of the entire list must take place to keep the matrix's structural integrity.
Suggestion: Use the $filter('matrical')($scope.list) syntax in combination with $scope.$watch and recompile/calculate item-positions for the matrix.
Cheers!

Resources