I am trying to call function inside condition in render function, only if condition is true.
On line #3 of following code.
{this.props.xarray.map((heading, index) =>
{return heading.headingis.toLowerCase().indexOf('mobile') != -1 ?
{this.setcheckstate()} //THIS IS FUNCTION
<option value="{heading.headingis}" key={index} selected>{heading.headingis}</option>
:
<option value="{heading.headingis}" key={index}>{heading.headingis}</option>
}
)}
But this is returning error:
Syntax error: this is a reserved word (51:10)
I want to change the state if condition is true.
I am trying to call function inside condition in render function, only if condition is true.
On line #3 of following code.
{this.props.xarray.map((heading, index) =>
{return heading.headingis.toLowerCase().indexOf('mobile') != -1 ?
{this.setcheckstate()} //THIS IS FUNCTION
<option value="{heading.headingis}" key={index} selected>{heading.headingis}</option>
:
<option value="{heading.headingis}" key={index}>{heading.headingis}</option>
}
)}
But this is returning error:
Syntax error: this is a reserved word (51:10)
I want to change the state if condition is true.
Share Improve this question asked Sep 21, 2017 at 8:03 Noman AliNoman Ali 3,34013 gold badges47 silver badges79 bronze badges 1- what does the function do? what does it return? – paqash Commented Sep 21, 2017 at 8:12
3 Answers
Reset to default 3Why don't you drop the ternarny ? It's sometimes clearer and cleaner to write a plain if
statement IMO.
{
this.props.xarray.map((heading, index) => {
if (heading.headingis.toLowerCase().indexOf('mobile') != -1) {
this.setcheckstate();
return <option value="{heading.headingis}" key={index} selected>{heading.headingis}</option>
}
return <option value="{heading.headingis}" key={index}>{heading.headingis}</option>
})
}
You need to put the condition outside of the return because that is not valid syntax.
It will be like this, Outside return of render method
const { xarray } = this.props;
Inside the return method of render()
{xarray.map((heading, i) => {
const { headingis } = heading;
const condition = headingis.toLowerCase().indexOf('mobile') != -1;
return (
condition && this.setCheckState() ?
<option value={headingis} key={i} selected>{headingis}</option> :
<option value={headingis} key={i}>{headingis}</option> :
);
}}
I am sorry I did all the destructing, but it's just a habit, i like clean code. Anyways if you only want to show a selected based on a condition, you can also do something like this as well.
{xarray.map((heading, i) => {
const { headingis } = heading;
const condition = headingis.toLowerCase().indexOf('mobile') != -1;
return (
condition && <option
value={headingis}
key={i}
selected={() => this.setCheckState}
>
{headingis}
</option>
);
})}