Reputation: 201
I have code as below. Where I am trying iterate domains and get it comma separated. Even if I am assigning directly arr = selectedOption.EmailDomainlist then also it's not comma separated after each domain. I am trying to display those domains in UI like
<div> Allowed domains: {this.state.domainOptions} ? {this.state.domainOptions} : 'N/A' </div>
selectedOption = {
EmailDomainlist : ["gmail.com", "yopmail.com"]
}
this.state = {domainOptions : []}
domainList = (selectedOption) => {
let arr = [];
selectedOption &&
selectedOption.EmailDomainlist.map((domain) => {
arr.push(domain);
});
this.setState(() => ({ domainOptions: arr }));
};
output : gmail.comyopmail.com
Expected output should be like comma separated after each domains: gmail.com,yopmail.com
How can we achieve this?
how can we add ternary operator in div tag?
<div> Allowed domains: {this.state.domainOptions} ? {this.state.domainOptions.join(', ')} : 'N/A' </div>
the above code is displayed in UI as Allowed domains: ( ? : N/A)
Upvotes: 0
Views: 186
Reputation: 895
You can just use join instead of iterating over the items:
<div> Allowed domains: {this.state.domainOptions ? this.state.domainOptions.join(', ') : 'N/A' } </div>
Upvotes: 2
Reputation: 5428
Join will do this for you. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
You probably don't need to store it in state either. In general, I wouldn't store anything in state that can be derived otherwise.
const selectedOption = {
EmailDomainlist : ["gmail.com", "yopmail.com"]
};
console.log(selectedOption.EmailDomainlist.join(","));
Upvotes: 2