How to use conditional to generate element on the page - reactjs

for (var k = 0; k < 10; k++) {
if (k % 2 === 0) {
weatherText = <div className="in_break">
}
weatherText += <div className="eachD" key={k}>
<div>
{
countIt === 0 ? (currDate.getHours() > 12 ? "Tonight" : "Today") : dayOfWeek[weekDay]
}
</div>
<div>
{
getDate
}
</div>
<div>
{
<ReturnIcon />
}
</div>
</div>
if (k % 2 === 0) {
weatherText += </div>
}
}
What I am looking to do is group all the eachD by two inside the `in_break' div
But I keep getting:
Parsing error: Unexpected token 'weatherText = </div>'
This is the layout:
in_break
eachD
eachD
in_break
eachD
eachD
in_break
eachD
eachD
...
Please help me resolve my issue

UPDATED
I hope this find it's way to your demand:
setWeatherTextItems = (countId, currDate, dayOfWeek, weekDay, getDate) => {
// you make sure all the variables such like countId and currDate are available inside this function.
const items = [];
for (var k = 0; k < 10; k++) {
items.push(
<div className="eachD" key={k}>
<div>
{countIt === 0
? currDate.getHours() > 12
? "Tonight"
: "Today"
: dayOfWeek[weekDay]}
</div>
<div>{getDate}</div>
<div>{<ReturnIcon />}</div>
</div>
);
}
return items;
}
renderInBreak = () => {
const items = this.setWeatherTextItems();
const inBreakItems = [];
let breakBlock = [];
let newBreak = false;
items.forEach((textItem, index) => { //1
if(!newBreak) {
breakBlock.push(textItem);
if(index + 1 === items.length){
inBreakItems.push(breakBlock);
}
} else {
inBreakItems.push(breakBlock);
breakBlock = [];
breakBlock.push(textItem);
//without this condition check, the last element will be left out of an odd array length
if(index + 1 === items.length) {
inBreakItems.push(breakBlock)
}
}
if(index % 2) newBreak = true; //false
else newBreak = false; //false
});
return inBreakItems.map(twoTextWeatherItems => (
<div className="in_break">
{twoTextWeatherItems}
</div>
))
}
render(){
<div>
{this.renderInBreak()}
</div>
}
OLD
React is supposed to handle things differently, maybe this will work:
Define a method in your component that will set your items:
setWeatherTextItems = (countId, currDate, dayOfWeek, weekDay, getDate) => {
// you make sure all the variables such like countId and currDate are available inside this function.
const items = [];
for (var k = 0; k < 10; k++) {
items.push(
<div className="eachD" key={k}>
<div>
{countIt === 0
? currDate.getHours() > 12
? "Tonight"
: "Today"
: dayOfWeek[weekDay]}
</div>
<div>{getDate}</div>
<div>{<ReturnIcon />}</div>
</div>
);
}
return items;
}
in your render method, or where you are willing to render these items:
render(){
<div className="in_break">{this.setWeatherTextItems()}</div>
}
Read more about how to render things in a loop.
You can add the conditions you want inside the for loop, or where it makes sense to you.

Not sure if the logic would work in a react environment but as far as I can see from your plain code when you are going to add the 'in_break' div aren't you just assigning the whole whetherText again instead of joining text to it?
Shouldn't this:
if (k % 2 === 0) {
weatherText = </div>
}
be written like this?
if (k % 2 === 0) {
weatherText += </div>
}
Edit following the typo correction:
I tried to run your code on codepen to have a quicker and easier understanding on how to find a solution.
I created an helper function with your code then I returned
<div className="Container" dangerouslySetInnerHTML={{__html: weatherText}}></div>
This enables you to have the result you are looking for. Only the even elements have the 'in_break' class.
Hope this helped and let me know if this is not correct.
Codepen: https://codepen.io/dpgian/pen/EBzRmX

Related

push object to array of arrays vue re-rendering failing

I have this weird issue where I can't seem to push an object to an array of arrays.
I am able to log the value of groups....but I can't update it.
here's my function to push to the groups array under a given set of conditions
calcExclusion: function(){
this.hideExclusionGroups = true //hides the exclusion groups from app before calculations
for(var i = 0; i < this.exclusionGroups.length; i++){
if(this.numberOfGroups < this.exclusionGroups.length){
alert('could not calculate, there are more exclusion groups than groups')
return
}
for(var j = 0; j < this.exclusionGroups[i].students.length; j++){
if(this.exclusionGroups[i].students.length == 1){
alert ('could not calculate, groups must be bigger than 1')
return
}
//console.log('group number', g,'student to add',this.exclusionGroups[i].students[j])
if(j < this.numberOfGroups){
this.groups[i].push(this.exclusionGroups[i].students[j].first_name)
console.log(this.groups[i])
}
}
}
},
here is where I render the data
<div v-for="(group, index) in groups" class="d-inline-block bg-white p-2 m-2 border rounded">
<span>Group {{ index + 1 }}</span>
<ul>
<li class="groupItems" v-for="student in group">
{{ student.first_name }}
<input type="hidden" :name="'group['+index+']'" :value="student.id">
</li>
</ul>
</div>
I am able to edit 'groups' to some extent but groups is referencing the computed prop here
computed: {
groups: function () {
if(! Number.isInteger(this.numberOfGroups)) {
console.log('mal');
return [];
}
const array = [];
for (let j = 0; j < this.numberOfGroups; j++) {
array[j] = [];
}
let i = 0;
this.students.forEach((student) => {
const x = i % this.numberOfGroups;
if(student.include === false){
array[x].push(student);
}
i++;
});
return array;
},
},
You are updating the results of a computed property. The result is not reactive, that's why you see that your code is updating the groups array, but you don't see any changed in the DOM.
You need to move the logic from calcExclusion inside the computed method for groups.

Angular 6 *ngFor display different styles for first, odd, even and last

I am learning Angular 6 and just trying to put togheter some of the stuff I have learned and I am currently running into an issue that I cannot find an answer to. I am trying to change the style of a LI using *ngFor depending if the index is First, Last, Odd or Even. So far everything works but I can't figure out how to do it for the Last because everything I add a new object to my list, it is obviously the last so it render the color for the last.
I understand how to do it but the real problem is that I am adding stuff dynamicly to my list from a form and I'm not sure how to evaluate the Last so that the others become to right color.
Keep in mind that I am still a newb and it might look messy and I also understand that some client-side validations I am doing are probably not optimal or required since HTMl5 but I made it to learn.
Here is my code for my component HTML
>
<h1>List of courses :</h1><br>
<div *ngIf="courses.length > 0; then coursesList else noCourses"></div>
<ng-template #coursesList>
<h2>List of Courses :</h2>
<ul *ngFor="let course of courses; index as i;">
<li [ngStyle]="{'background-color':getColor(i)}" style="color: white;">
<strong>Index : </strong>{{i}} <strong>ID : </strong>{{course.id}} <strong>Name</strong> : {{course.name}}
<button (click)="onRemove(i)">Remove</button>
<button (click)="onModify(i)">Modify</button>
</li>
</ul>
</ng-template>
<ng-template #noCourses>
<h5>There are no courses in this list. Use the form bellow to add some.</h5>
</ng-template>
<div (keyup.enter)="onAdd()">
<span>ID : <input type="number" (keypress)="checkNumber($event)" [(ngModel)]="fields.id" placeholder="Enter an ID"></span>
<span>Name : <input type="text" [(ngModel)]="fields.name" placeholder="Enter a NAME"></span>
<button (click)="onAdd()">Add</button>
<button (click)="onClear()">Clear</button>
</div>
<div *ngIf="isNotNumber" style="background-color: red; color:black"><strong>ID can only be numbers !</strong></div>
<div *ngIf="noValues" style="background-color: red; color:black"><strong>Please fill all fields !</strong></div>
<div *ngIf="noModifyValues" style="background-color: red; color:black"><strong>To modify enter all informations!</strong></div>
Code for .TS
>
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
noValues: boolean;
noModifyValues: boolean;
isNotNumber: boolean;
fields: Courses = {id: null, name: null};
courses: Array<Courses> = [];
viewMode: string = null;
checkNumber($event) {
if ($event.keyCode != 13) {
isFinite($event.key) ? this.isNotNumber = false : this.isNotNumber = true;
}
}
onAdd() {
if (!this.fields.id || !this.fields.name) {
this.noValues = true;
} else {
this.courses.push({id: this.fields.id, name: this.fields.name});
this.fields.id = null;
this.fields.name = null;
this.noValues = false;
}
}
onRemove(i) {
this.courses.splice(i, 1);
}
onClear() {
this.courses = [];
this.fields.id = null;
this.fields.name = null;
this.noValues = false;
}
onModify(i) {
if (!this.fields.id || !this.fields.name) {
this.noModifyValues = true;
} else {
this.courses[i].name = this.fields.name;
this.courses[i].id = this.fields.id;
this.noModifyValues = false;
}
}
getColor(i){
if (i % 2 === 0 && i != 0){i = 'odd';}
switch (i) {
case i = 0 : return 'orange';
case i = 'odd' : return 'blue';
}
return 'red';
}
}
interface Courses {
id: number;
name: string;
}
Image of the code in action for better understanding.
If you only want change the background-color you can use [style.background-color] and you can use ternary operator in the .html
<ul *ngFor="let course of courses; let index=i;
let odd=odd;
let last=last;
let first=first">
<li [style.backgound-color]="first?'orange':last?'purple':odd?'blue':'red'">
...
</li>
</ul>
Try something like this
getColor(i){
if (i % 2 === 0 && i != 0){i = 'odd';}
if (this.courses && (this.courses.length - 1 === i)) {i = 'last'}
switch (i) {
case i = 0 : return 'orange';
case i = 'odd' : return 'blue';
}
return 'red';
}
Hope it works - Happy coding !!
Thanks Rahul. The part I was missing is evaluating if there is something in courses. However, I had to had a few more lines to Odd and Last as follow :
getColor(i){
if (this.courses && i != 0 && (this.courses.length - 1 === i)) {i = 'last'}
if (i % 2 === 0 && i != 0 && i != 'last'){i = 'odd';}
switch (i) {
case i = 0 : return 'orange';
case i = 'odd' : return 'blue';
case i = 'last' : return 'purple';
}
return 'red';
}
Quick question. It seems like a whole lot of IF and && and checking specific things. Is that the way to do it properly?
You could use if else ladder instead of mixing up if else and switch and assignments like given below
getColor(i)
{
if(this.courses)
{
if(i==0)
return "orange";
else if(i==this.courses.length-1)
return "purple";
else if (i%2==0)
return "red";
else
return "blue";
}
}

How to dynamically use object property as width in AngularJS (in ng-repeat)?

I cannot get the object's property to be read in ng-style(shape.radius || shape.length). I can't even get 1 to work at the moment, but would like to have an or statement included. Similar to my ng-class.
There is a button to generate shapes, and the shapes were created with a random size. Here is my code:
html:
<div ng-controller='ShapeController as sc'>
<div>
<p><input type="submit" value="Generate Random Shapes" ng-click="sc.generateShapes()"/></p>
<div ng-repeat="shape in sc.shapes">
<div class="shape" ng-class="{circle: shape.radius, square: shape.length}" ng-style="{'width': shape.length}"></div>
</div>
</div>
</div>
script:
var app = angular.module('app', []);
app.controller('ShapeController', function(){
var vm = this;
vm.shapes = [];
vm.randomShapes = [];
vm.width = 30;
function createCircle(radius) {
let circle = new Circle(radius);
vm.shapes.push(circle);
} // end createCircle
function createSquare(length) {
let square = new Square(length);
vm.shapes.push(square);
} // end createSquare
vm.generateShapes = function() {
let times = 50
for (let i = 0; i < times; i++) {
createCircle(getRandomNumber());
}
for (let i = 0; i < times; i++) {
createSquare(getRandomNumber());
}
sort(vm.shapes);
console.log(vm.shapes);
}; // end generateShapes
}); // end controller
function sort(arr) {
arr.sort(function(a,b){
return b.getArea() - a.getArea();
});
} // end sort function
function getRandomNumber() {
return Math.random() * (100-1) + 1;
}
width should be either in px(some unit like em, pt, etc) or %
ng-style="{'width': shape.length + 'px'}"

var statement throwing error in react.js

So im trying to create a counter to determine if a verticle bar should be rendered in my component but everytime I try to create the counter variable outside of the map function it throws an error:
return (
<div className={css.classNames.div} style={css.styles.div}>
{ var counter = [];
this.props.children.map(function(child){
counter.push('1')
if (counter.length !== this.props.children.length){
return <li className={css.classNames.list}>{child}</li>;
} else {
return <li className={css.classNames.list}>{child}</li>;
}
}.bind(this))
}
</div>
);
There must be a way to do it. Does anyone know the problem?
Move the var counter = []; to before the return.
var counter = [];
return (
<div className={css.classNames.div} style={css.styles.div}>
{this.props.children.map(function(child){
counter.push('1')
if (counter.length !== this.props.children.length){
return <li className={css.classNames.list}>{child}</li>;
} else {
return <li className={css.classNames.list}>{child}</li>;
}
}.bind(this))}
</div>
);

How to show element once in ng-repeat

I need to loop through a list order by price and as soon as the price is not there then I show a message with unavailable but I don't want to show it for each empty element. I'm using angular 1.2
<div ng-repeat="item in list | orderBy: 'cost'">
<div ng-if="cost == 0 and not already shown">Sorry the following are unavailable</div>
<div>...my item here...</div>
<div>
You can conditionally display two spans - one if it's 0 (your 'not available' message) and another for anything else.
<ul>
<li ng-repeat="d in newData track by $index">
<span ng-show="d > 0">{{d}}</span>
<span ng-show="d === 0">Not Available</span>
</li>
</ul>
The data can be passed through a function to pull all the 0 after the first one:
$scope.data = [1,2,3,0,1,0,0,1,0,2]
$scope.pullDupes = function(array) {
var newArray = [];
var zero;
for(var i = 0; i < array.length; i++) {
if (array[i] !== 0) {
newArray.push(array[i])
}
if (array[i] === 0 && !zero) {
zero = true;
newArray.push(array[i])
}
}
return newArray;
}
$scope.newData = $scope.pullDupes($scope.data);
Plunker
You can show only the first message see here :
<div ng-repeat="item in list | orderBy: 'cost'">
<div style="color:red" ng-show="item.cost == 0 && $first">Message Goes Here</div>
<hr>
<div>{{item.name}} - Price : {{item.cost}}</div>
</div>
and here is a plunker for it :
http://plnkr.co/edit/RwZPZp9rFIChWxqF71O7?p=preview
also the ng-if you are using it wrong you need to do it like this item.cost for the next time
Cheers !
Here is the best way I could find to get it done.
Markup
<div class="sold-out-message" ng-if="displaySoldOutMessage(item)">Sorry, sold out</div>
Controller
$scope.firstSoldOutItemId = false;
$scope.displaySoldOutMessage = function(item) {
if ( item.cost ) return false;
$scope.firstSoldOutItemId = $scope.firstSoldOutItemId || item.id;
return item.id == $scope.firstSoldOutItemId;
};
You can try to use $scope.$whatch with a boolean variable like this:
<div ng-model="actualItem" ng-repeat="item in list | orderBy: 'cost'">
<div ng-if="cost == 0 && oneMessage == true">Sorry the following are unavailable</div>
<div>...my item here...</div>
<div>
</div>
And in your controller you look at actualItem :
$scope.oneMessage = false;
var cpt = 0; // if 1 so you stop to send message
$scope.$watch('actualItem',function(value){
if(value.cost == 0 && $scope.oneMessage == false && cpt < 1)
// i don't know what is your cost but value is your actual item
{
$scope.oneMessage = true;
cpt++;
}
else if($scope.oneMessage == true)
{
$scope.oneMessage == false;
}
});
I am not sure about this but you can try it. It's certainly not the best way.

Resources