Star-rating component logic implementation in react - reactjs

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" />
);
};

Related

reactjs pagination showing undesired element when selecting backwards

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.

Limit shown entries of nested ng-repeat

I have an object like this:
data = {
element1: ["content11", "content12"],
element2: [],
element3: ["content31"],
element4: ["content41", "content42", "content43"]
}
Displaying everything with nested ng-repeat is straightforward:
<div ng-repeat="element in data">
<div ng-repeat="content in element">
{{content}}
</div>
</div>
Which gives me the expected output:
content11
content12
content31
content41
content42
content43
The number of elements is known, but the size of the arrays varies.
Now I'm struggling to limit the list of displayed elements to 4.
To spice things up, I want to show the first array entries first, then continue with the second, and so on. Which leads to the following code:
iteration = [0,1,2,3] //because I want to limit everything to 4 elements and don't care for more
<div ng-repeat="i in iteration">
<div ng-repeat="content in data">
{{content[i]}}
</div>
</div>
Again the expected output, but still struggling with the limit:
content11
content31
content41
content12
content42
content43
I tried to work with $parent.$index and $index, but was not successful to build a working counting function.
Unfortunately, I have to evaluate this data structure in each line of a large table and must keep an eye on performance.
Refactoring the object is for legacy reasons not possible.
I came up with this:
<div ng-repeat="i in iteration">
<div ng-repeat="(type, content) in data" ng-show="content[i] && countPreviousElements(data, i, $index) <= limit">
{{content[i]}}
</div>
</div>
and
$scope.countPreviousElements = function(data, iteration, index){
var sum = 0;
var i = 0;
for(var key in data){
if(i<=index){
sum += data[key].length > iteration+1 ? iteration+1 : data[key].length;
}else{
sum += data[key].length > iteration ? iteration : data[key].length;
}
i+=1;
}
return sum;
};
http://plnkr.co/edit/0mzTBZIDuk39BFjJ2wRi?p=preview
This seems to work as I expected and the 'limit' can be changed at runtime.
Let's discuss the performance. This function is called for each array element in data. After an analysis of the productive data, the sum of all elements within the arrays in data does not grow beyond 20 in every row, usually much smaller.
Inside the function we loop once over the length of data, which is fixed right now to 9 and not expected to grow.
If I have to do this several times in a table the costs still remain linear.
Hopefully there is no problem for this "on the fly" solution.

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 to show only 25 element at one time?

I am trying make table view in ionic using angular js .but I have lot of data to show around 5000 object .So after getting data my UI hang because it is printing the data on dom.So I want to implement lazy loading so that only 100 element is visible to me or only 100 element present in dom only .When user scroll it download another 100 objects or element and removing the uppers element so that my UI not hang .can we do in angular js
I will show you how my UI hang .take a look my example here
my loader hang for around 5 seconds ..
So I tried with infinite scroll in my demo so that I am able to show only 100 element at one time
here is my code of infinite scroll But I am not able to display 100 element at one time I didnot get any error also
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="canWeLoadMoreContent()" distance="10%">
<div class="row" ng-repeat="column in _list | orderBy: sortval:reverse | filter: query">
<div class="col col-center brd collapse-sm" ng-repeat="field in column.columns" ng-show="invoice_column_name['index'].fieldNameOrPath===field.fieldNameOrPath">{{field.value}}</div>
<div class="col col-10 text-center brd collapse-sm"></div>
</div>
</ion-infinite-scroll>
</ion-content>
Updated Plunker
I took a little different approach then the others.
There is a variable at the top of the controller called showitems. This controls how many items you want to show at a time. The counter variable will keep track of where how many items are shown. Initially, the value is set to the showitems value since we're going to prepopulate the dataset with the first items immediately in the ShowViewAfterSuccess function.
var showitems = 100;
var counter = showitems;
In your ShowViewAfterSuccess function, I added the data to a scope variable called $scope.total_invoice_records.
Next, I run the first array slice on the data. This will pass the first x number of records to the $scope.invoice_records based on the value set in the showitems variable. This initializes the view with the first set of records.
$scope.total_invoice_records=data.records;
$scope.invoice_records = $scope.total_invoice_records.slice(0, showitems);
I added a loadMore function that simply grabs the next x number of records from the total record set and concatenates them to the current set in $scope.invoice_records and increments the counter. loadMore will also check if there are still more records to load and broadcasts the message to the ionic infinite scroll directive to remove the spinner.
$scope.noMoreItemsAvailable = false;
$scope.loadMore = function() {
var next = $scope.total_invoice_records.slice(counter, counter+showitems);
$scope.invoice_records = $scope.invoice_records.concat(next);
counter = counter+showitems;
if (counter>=$scope.total_invoice_records.length) {
$scope.noMoreItemsAvailable = true;
}
$scope.$broadcast('scroll.infiniteScrollComplete');
};
Most importantly, remember to set the immediate-check attribute on the infinite scroll element to false:
<ion-infinite-scroll immediate-check="false" ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="10%"></ion-infinite-scroll>
You need to set up a pagination rather than use infinite scroll; or keep the functionnality of infinite scroll as is.
but if you wish to still use infinite scroll, then when you load your next datas into _list, just before filling in the new elements, clean your _list with a _list.length= 0
But you will have sideeffects that I don't know such as :
- how to load the 100 first elements ?
- the page will jump from full with 100 elements, cleaned to 0, and filled with next 100. This will lead, I assume, to an unpleasant effect
My configuration of ion-infinite is the following :
<ion-infinite-scroll
ng-if="!myModel.maxItemLoaded"
icon="ion-loading-c"
on-infinite="loadMoreData()"
distance="10"
>
Which means :
- when user scroll gets on the 10 last % of the page height, loads loadMoreData
If user never scoll, then he has only the first data shown.
Edit:
Here is an updated plunkr
http://plnkr.co/edit/B5KCbc8hr66upCXMvXSR?p=preview
Few remarks :
- the infinite scroll directive is independent and shall not surroung your table
- accessing to to index is done by $index, not with 'index'
- the load functionnality has been modified to load the next 100 elements
$scope.populateList = function() {
var size = $scope._list.length;
var maxSize = size + 100;
if (maxSize > $scope.invoice_records.length)
maxSize = $scope.invoice_records;
console.log("populateList",size,maxSize,$scope.invoice_records)
for (var i = size; i <= maxSize; i++) {
console.log("push",$scope.invoice_records[i])
$scope._list.push($scope.invoice_records[i]);
}
console.log($scope._list.length);
$scope.$broadcast('scroll.infiniteScrollComplete');
}
Angular should work with 5000 object, if it is read only , you can use one time binding
An expression that starts with :: is considered a one-time expression.
One-time expressions will stop recalculating once they are stable,
which happens after the first digest if the expression result is a
non-undefined value (see value stabilization algorithm below).
<span ng-bind="::name"></span>
I don't know infinite scrolling, but if I had to implement something like that i would have used ng-filter 'limit'.
ng-repeat="column in _list | limit : limitValue"
And then bind any button/scroll event to
$scope.limitValue = $scope.limitValue + "10";
Ideally you should not have brought this much data in 1 call. Now, if you have, you can achieve this by a small tweak.
Break your data in chunk of 100. And set that 100 in $scope.
var brokenData = [];
var totalData = x; // Total 5000 records
var pages = parseInt(totalData.length/100);
if(totalData.length % 100 !== 0) {
pages += 1;
}
for (var i = 0; i < pages; i++){
if(i == pages - 1) {
brokenData.push(totalData);
} else {
brokenData.push(totalData.splice(0,100));
}
}
Now set
$scope.pages = pages;
And for 1st page or for 1st time,
$scope.pageData = brokenData[0];
$scope.currentPage = 0 + 1;
This will show only 100 records on your page and sets current page as 1.
Now you can choose any pagination tool or bind window scroll events and just update the above 2 things
Like for 2nd page
$scope.pageData = brokenData[1];
$scope.currentPage = 1 + 1;

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