How to pass if condition loop output to a variable in reactjs - arrays

I need help to solve this
let someVar
render(
{
this.props.someData.map((items) =>
items.someotherData.map((item) =>
(item.data1 > 5 && item.data2 == "more") ? classNames({ "classname1": true })
: (item.data1 > 5 && item.data2 == "less") ? classNames({ "classname2": true })
: classNames({ "classname3": true })
))
}
<div className = { someVar } ></div>
)
I need my output of if loop to be pass to the variable
I tried many method. Nothing worked. Please give the solution

render() {
let someVar
this.props.someData.forEach(items =>
items.someotherData.forEach(item =>
item.data1 > 5 && item.data2 == 'more'
? someVar = 'classname1'
: item.data1 > 5 && item.data2 == 'less'
? someVar = 'classname2'
: someVar = 'classname3'
)
)
return <div className={someVar}></div>
}
I didn't really get what you were trying to do. Are you calling some function with the class names or something? Here is my best try to solve your problem though.
First we create the variable,
Then we do data processing. You shouldn't use map but instead the forEach if you are not returning anything. You are also overwriting the variable for each item (is this preferred behaviour?).
Then we actually return the React part of the code. Render function always needs to return JSX or null. Inside JSX we can use the someVar in the className. The final value of className needs to be a string. That's why we are putting strings to the someVar.

Related

Object with similar attribute names loop, React

I have object with attributes like tabletA, tabletB, tabletC, containing allways string.
The same object contains other attributes as well, like company, phone.
My goal is to look at attributes in one line, and display only tablet attributes, where are strings, with values.
So I imagine code to look like something like this:
{referenceTexts.[tablet].length > 0 && (
<div>
referenceTexts.[tablet]
</div>
)}
{Object.entries(referenceTexts)
.filter(([key, val]) => key.startsWith('tablet') && val.length > 0)
.map(([_, val]) => (
<div>{val}</div>
))}
const tabletValues = Object.keys(referenceTexts)
// get keys that start with "tablet"
.filter(key => key.startsWith('tablet'))
// get their values
.map(key => referenceTexts[key])
// get only values that are not empty
.filter(value => (value || '').length > 0);
Then
{tabletValues.map(value => <div>{value}</div>)}
Note that the order of the values is undefined so you might want to add some kind of sorting.
hopefully I got you. You want something like this :
{Object.keys(referenceTexts).map((key) => {
if (key.substr(0, 6) === "tablet") {
return <h1>{referenceTexts[key]}</h1>;
}
})}

Using a variable that has been defined inside render, to use it inside return

so I'm getting certain redmax and redmin values through props and I've stored them in a variable. The below code is inside render. This is how it looks:
if(props.gauge.id === 8){
let redMaxPressure = (props.gauge.params.red_max).split(',').map(function(i){
return parseInt(i,10)
})
let redMinPressure = (props.gauge.params.red_min).split(',').map(function(i){
return parseInt(i,10)
})
console.log('RedMax',redMaxPressure)
}
Now, I want to use those values inside the 'rect' svg but I'm unable to use that as it's throwing an error.
<rect
x={-0.305}
y={0.63}
rx={0.02}
width={0.6}
height={0.3}
fill={props.size !== 'small' && props.value <= redMaxPressure[0] ? rectColor : props.size === 'small' && props.value >=redMaxPressure[1] ? rectColor : '#ffffff00' }
stroke={'black'}
stroke-width={0.02}
/>
I'm getting an error for redMaxPressure[0] and redMaxPressure[1]. Is there a different way to use those values stored?
Note: The rect svg is inside return.
Your redMaxPressure, redMinPressure are not in scope of rect element, because currently they live (variables lifetime) only in if scope, so their values are undefined.
You should ensure they in scope:
let redMaxPressure = DEFAULT_MAX;
let redMinPressure = DEFAULT_MIN;
if(props.gauge.id === 8){
redMaxPressure = ...
redMinPressure = ...
}
return <rect fill={props.size !== 'small' && props.value <= redMaxPressure[0] ? rectColor : props.size === 'small' && props.value >=redMaxPressure[1] ? rectColor : '#ffffff00' } />

adding active class bootstrap carousel at repeat data just on first key in react app

I'm looking how to make a repeat item carousel which has if just key 0 that have class action if I using it in return it's error and if I using variable in return pug .carousel-item${activeornot}
return _.map(this.props.editor_pick_data, function (value, key){
if(key == 0){
}
return (
pug`
.carousel-item.active(key=${key}, style=${{display: 'relative'}})
.col-md-3.col-sm-6.col-xs-12npm
a.thumbnail(href="#")
img.img-responsive(src=${value.item.images[1].big_thumbnail})
`
)
})
It looks like you're just trying to add active class if key === 0. I think you can have a className variable as well:
className=${key == 0 ? 'active' : ''}
-
renderCarouselItem() {
return _.map(this.props.editor_pick_data, function(value, key) {
return (
pug`
.carousel-item(key=${key}, style=${{display: 'relative'}}, className=${key == 0 ? 'active' : ''})
.col-md-3.col-sm-6.col-xs-12npm
a.thumbnail(href="#")
img.img-responsive(src=${value.item.images[1].big_thumbnail})
`
);
})
}
Maybe you can do something like this:
className={`carousel-item ${key == 0 ? 'active' : ''}`}
this work but i dont know this is the best practice
renderCarouselItem() {
return _.map(this.props.editor_pick_data, function (value, key){
let html = [];
if(key == 0){
html.push(pug`
.carousel-item.active(key=${key}, style=${{display: 'relative'}})
.col-md-3.col-sm-6.col-xs-12npm
a.thumbnail(href="#")
img.img-responsive(src=${value.item.images[1].big_thumbnail})
`)
}else{
html.push(pug`
.carousel-item(key=${key}, style=${{display: 'relative'}})
.col-md-3.col-sm-6.col-xs-12npm
a.thumbnail(href="#")
img.img-responsive(src=${value.item.images[1].big_thumbnail})
`)
}
return (
pug`
${html[0]}
`
)
})
}

React className with ternary operator add class 'null'

I'm trying to conditionally apply a class to my component using an expression like this:
.map(function(list, index) {
<div className={"myClass " + (position === index ? 'active' : null)}>
}
But it keeps adding null as class, with an end result like this:
<div class="myClass active">...
<div class="myClass null">...
This is a simple example, with only 2 class names, so I could just replace null with the default class name. But in a more complex layout, I would need to duplicate the same name over and over again.
Is there a better approach to solve this problem?
You could use an empty string '' instead of null like:
.map(function(list, index) {
<div className={"myClass " + (position === index ? 'active' : '')}>
}
Also map should return a value:
.map(function(list, index) {
return <div className={"myClass " + (position === index ? 'active' : '')}>;
}
If you have multiple classes, you might consider building the list of classes from an array:
var classes = ["myClass"];
if (position === index) {
classes.push('active');
}
return (
<div className={classes.join(' ')}>
...
</div>
);
You can also consider using a helper function that will generate the className string from an object like this:
var classes = {
myClass: true,
active: position === index
};
classnames is one such utility (not the only one).
Remove the space from "myClass " to "myClass", then replace null with an empty string ""
.map(function(list, index) {
<div className={"myClass" + (position === index ? 'active' : "")}>
}
just use https://www.npmjs.com/package/classnames:
usage example:
<div className={cn({"active": position === index })} ></div>
Use && short-circuiting: className={"myClass " + (position === index && 'active')}
In this way, if position === index is false, because we are using &&, we short-circuit. JS skips over 'active' and we just move on with our lives.
React Solution:
className={`myClass ${index ? "active" : ""}`}
Different syntax
className={`myClass ${index && "active"}`}

AngularJS forEach function - cannot get to resolve to true

I have the following code in my controller:
$scope.checkSchedule = function (value) {
var result = false;
angular.forEach($scope.shifts, function (obj) {
if (obj['PublishedEmployee.Id'] === value && result === false) {
result = true;
}
});
return result;
};
My $scope.shifts is an array of objects. Each object contains another object, PublishedEmployee and that object has a property of Id.
My goal is to iterate over the $scope.shifts objects and if the PublishedEmployee.Id property == $scope.currentId then resolve the function to be true.
In my HTML I have the following:
ng-show="checkSchedule(currentId)"
So, if the function resolves to true, the element will display. However, I'm always receiving false, what am I missing to have this resolve accordingly?
Pictures:
Your problem is that you are checking for the literal property "PublishedEmployee.Id" and not the sub property "Id" of "PublishedEmployee".
Change
if (obj['PublishedEmployee.Id'] === value && result === false)
to
if (!result && obj.PublishedEmployee && obj.PublishedEmployee.Id === value)
This will check for the existence of a PublishedEmployee property before attempting to compare its Id property.
If you're just wanting to check if any of the $scope.shifts match, you can use Array.prototype.some.
return $scope.shifts.some(function(obj) {
return obj.PublishedEmployee && obj.PublishedEmployee.Id === value;
});
In theory this will work if your data is as you say...
<div ng-repeat="item in shifts">
<div ng-show="item.PublishedEmployee.Id == currentId">
Matched
</div>
</div>

Resources