Getting an error when add i++ react js es6 jsx - reactjs

I am getting an error when adding additional line to code (i++), i would like to know where the code should be added.
let i = 1;
this.props.client_name.split(",").map((entry0) => (
this.props.campaign_name.split(",").map((entry1) => (
this.props.adset_name.split(",").map((entry2) => (
( item.client_name.toLowerCase().indexOf(entry0.toLowerCase()) !== -1 && item.campaign_name.toLowerCase().indexOf(entry1.toLowerCase()) !== -1 && item.adsets_name.toLowerCase().indexOf(entry2.toLowerCase()) !== -1 )?
**i++**
(<Task key={item._id} id={item.adsets_id} i={key} item={item} date_from={this.state.date_from} date_to={this.state.date_to} campaign_name={this.state.campaign_name} adset_name={this.state.adset_name} />)
:
(null)
))
))
))
Thanks

Because you are using two expression here:
condition? i++ (<Task ..../>) : null;
Wrap them in (), Write it like this:
condition? (i++, <Task ..../>) : null;
First it will increment the value of i, then return the Task component.
Check MDN Doc for more details about ternary operator.
Check this snippet:
var a = 1;
var b = true? (a++, a): 0;
console.log('b', b);

Related

How to access values by key from modified React final form

I was making confirmation when the user tried to close the form by modified and values length > 0.
if (modified) {
return (
Object.keys(modified).filter(
(modifiedItem) => modified[modifiedItem] && values[modifiedItem]?.length > 0,
).length > 0
)
}
Everything is working fine until there are values with an array:
when I try to access by values[answers.0.icon] there is undefined, of course, it should be accessed by values.answers[0].icon, by is it possible to do it when iterating modified keys? Or another way should be appreciated.
Thank you beforehand.
Below screenshots of values:
Modified keys:
I'd suggest to include lodash and use the get function. This will resolve the "path" for you.
For example _.get(values, modifiedItem).
More info can be found at https://lodash.com/docs/4.17.15#get
you could add undefined and null in the if statement, to check if it's true and not undefined and not null before it filter else it will be null or you can put something else.
if (modified && modified !== undefined && modified !== null) {
return (
Object.keys(modified).filter(
(modifiedItem) => modified[modifiedItem] && values[modifiedItem]?.length > 0,
).length > 0
)
}
else {
null
}
You can perhaps check for such situation if its an array and treat it differently.
I agree with solution provided by #Stijn answer, however if you dont wanna carry unnecessary baggage of Lodash you can use below code.
const parseDeep = (obj, path, def) => (() => typeof path === 'string' ?
path.replace(/\[(\d+)]/g,'.$1') : path.join('.'))()
.split('.')
.filter(Boolean)
.every(step => ((obj = obj[step]) !== undefined)) ? obj : def
if (modified) {
return (
Object.keys(modified).filter(
(modifiedItem) =>
Array.isArray(modifiedItem) ?
modified[modifiedItem] && parseDeep(values, modifiedItem, false) : //modify as required
modified[modifiedItem] && values[modifiedItem]?.length > 0,
).length > 0
)
}

How can call multiple function in React ternary if else condition

I can not call multiple functions in react js if else ternary condition.
const preATCHandler = ( id, itemNumber ) => {
itemNumber > 0
? (setAtcBtn(false), setQty(itemNumber), dispatch(addToCart(id, Number(itemNumber))))
: (dispatch(removeFromCart(id)), setAtcBtn(true))
}
I can not call multiple functions in ternary operator because it is inline condition.
Finaly take help from wxker.
I use this.
const preATCHandler = ( id, itemNumber ) => {
if (itemNumber){
setAtcBtn(false);
dispatch(addToCart(id, Number(itemNumber)));
}else {
dispatch(removeFromCart(id));
setAtcBtn(true);
}
}

Multiple map on array React Native

Use multiple Map on array. I get error:
SyntaxError: C:\Users\Laptop15\Desktop\React Native\src\screens\Question.js: Unexpected token, expected "," (59:7)
I use function that: {PytaniePush(quizDane.quest1)}
function PytaniePush(myID) {
if(quizDane && quizDane.quest1 && myID){
myID.map((item, key)=>(
myID[key].map((item2, key2)=>(
return ({RadioPush(myID[key].item2)});
));
));
}
}
I want to console log with all elements in array and object:
quest1->array[Object(A,B), Object(A,B)]
Data look: that
I want to get:
A in 0 is ...
B in 0 is ...
A in 1 is ...
B in 1 is ...
You have an syntax error in your code. Here is right code.
function PytaniePush(myID) {
if (quizDane && quizDane.quest1 && myID) {
myID.map((item, key) =>
myID[key].map((item2, key2) => {
return RadioPush(myID[key].item2);
})
);
}
}
Next time when you will have a syntax error try to use Prettier to find error and improve format of your code.
There are some syntax errors in your code. Try this one.
function PytaniePush(myID) {
if(quizDane && quizDane.quest1 && myID){
myID.map((item, key) => myID[key].map((item2, key2) => {
return RadioPush(myID[key].item2);
} ));
}
}
Try to use an ES6 aware IDE. That way you will not stumble upon this kind of issues.

reactjs semantic-ui how to correctly modify a JSX tag conditionally

I have a tag that I want to define conditionally
<Table.Cell positive>{item}</Table.Cell>
Then, what's the correct way of doing it?
What I've done is substituting it with a function
{this.callme(item)}
and the function then returns this
callme = (item) => {
let res;
if (item && item > 3)
res = <Table.Cell positive>{item}</Table.Cell>
else if (item && item < -3)
res = <Table.Cell negative>{item}</Table.Cell>
else if (item)
res = <Table.Cell>{item}</Table.Cell>
else
res = <Table.Cell>..</Table.Cell>
return res;
But this is verbose. Then I've tried to modify things inside the tag but this is not allowed
<Table.Cell {mystate}>{item}</Table.Cell>
and then there the question. How can I modify a tag itself? How is it supposed to be written?
I would suggest a slight adjustment to your approach that returns the component directly, rather than assign and return via res:
callme = (item) => {
if (item && item > 3)
return (<Table.Cell positive>{item}</Table.Cell>)
else if (item && item < -3)
return (<Table.Cell negative>{item}</Table.Cell>)
else if (item)
return (<Table.Cell>{item}</Table.Cell>)
else
return (<Table.Cell>..</Table.Cell>)
}
That change aside, your general approach is good in that it's both readable and functionally correct.
Alternatively, you could revise your methods overall structure like so to minimize the total line count, and reduce four return statements down to one return statement:
callme = (item) => {
return (item ?
<Table.Cell negative={ item < -3 } positive={ item > 3 }>{item}</Table.Cell> :
<Table.Cell>..</Table.Cell>)
}
You can optimize callme method like this:
callme(item) {
if(item) {
return <Table.Cell positive={item > 3} negative={item < -3}>{item}</Table.Cell>
} else {
return <Table.Cell>..</Table.Cell>
}
}

Cannot read property 'toJS' of undefined

I have two arrays. But when one of them is null it gives the following error:
Cannot read property 'toJS' of undefined in that line
Here's the relevant call that triggers the error: {groupsGuney.toJS()}
Here's my declaration of the variables let groupsGuney, groupsKuzey;
And finally here are my two arrays. But when one of them is null it gives the error:
...
if (muso == 1) {
groupsGuney = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}
if (muso == 2) {
groupsKuzey = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}
var result = (
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsGuney.toJS() }
</div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsKuzey.toJS() }
</div>
</div>
);
return result;
}
}
export default DiscardMiniBoxArea;
Instead of doing:
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{groupsGuney.toJS()}
</div>
....
you should do:
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{groupsGuney && groupsGuney.toJS()}
</div>
....
Before calling a function on your object, you need to make sure it's there. If you're uncertain about your object having the function at all times, you will need an additional check, that makes sure toJS is there and that it's a valid function.
If that's the case, update what's inside your container to:
{groupsGuney && typeof groupsGuney.toJS === 'function' && groupsGuney.toJS()}
However, ideally, you would not render at all this specific group if what you would like to render is not there. You should move these checks to before you render your component.
My motivation here is mostly that my call .get of undefined poops itself really hard, and initializing properly all over the place helps, but doesn't catch all edge cases. I just want the data or undefined without any breakage. Specific type checking causes me to do more work later if I want it to make changes.
This looser version solves many more edge cases(most if not all extend type Iterable which has .get, and all data is eventually gotten) than a specific type check does(which usually only saves you when you try to update on the wrong type etc).
/* getValid: Checks for valid ImmutableJS type Iterable
returns valid Iterable, valid Iterable child data, or undefined
Iterable.isIterable(maybeIterable) && maybeIterable.get(['data', key], Map()), becomes
getValid(maybeIterable, ['data', key], Map())
But wait! There's more! As a result:
getValid(maybeIterable) returns the maybeIterable or undefined
and we can still say getValid(maybeIterable, null, Map()) returns the maybeIterable or Map() */
export const getValid = (maybeIterable, path, getInstead) =>
Iterable.isIterable(maybeIterable) && path
? ((typeof path === 'object' && maybeIterable.getIn(path, getInstead)) || maybeIterable.get(path, getInstead))
: Iterable.isIterable(maybeIterable) && maybeIterable || getInstead;
//Here is an untested version that a friend requested. It is slightly easier to grok.
export const getValid = (maybeIterable, path, getInstead) => {
if(valid(maybeIterable)) { // Check if it is valid
if(path) { // Check if it has a key
if(typeof path === 'object') { // Check if it is an 'array'
return maybeIterable.getIn(path, getInstead) // Get your stuff
} else {
maybeIterable.get(path, getInstead) // Get your stuff
}
} else {
return maybeIterable || getInstead; // No key? just return the valid Iterable
}
} else {
return undefined; // Not valid, return undefined, perhaps should return false here
}
}
Just give me what I am asking for or tell me no. Don't explode. I believe underscore does something similar also.

Resources