How to fetching the data except undefined in react js - reactjs

I want to retrieve some data from a JSON file. But if the data is not available i am getting undefined. How to remove undefined data from my output.
Here is the sample code I have tried.
import React from 'react';
const DisplayDataAtHome = () => {
const json_data=[{
"merchant_id": 1,
"medium_egg": 104,
"small_egg": 100,
"desi_egg": 110
}, {
"merchant_id": 2,
"big_egg": 90,
"medium_egg": 104,
"desi_egg": 112
}, {
"merchant_id": 3,
"big_egg": 95,
"small_egg": 104,
"medium_egg": 107
}]
console.log(json_data);
return (
<>
<div className="outerDiv">
{
json_data.map((val, i)=>(
<>
{
typeof val.big_egg === "undefined" ? null:
<div className="innerDiv">
<p align="left">Big Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.big_egg+"/-"}<button>ADD</button></p>
</div>
}
{
typeof val.desi_egg === "undefined" ? null:
<div className="innerDiv">
<p align="left">Small Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.small_egg+"/-"}<button>ADD</button></p>
</div>
}
{
typeof val.small_egg === "undefined" ? null:
<div className="innerDiv">
<p align="left">Desi Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.desi_egg+"/-"}<button>ADD</button></p>
</div>
}
</>
))
}
</div>
</>
)
}
export default DisplayDataAtHome;
My output should looks like ion one div I want to get all the data as one more div. Just forgot about div. I want to fetch the data, the undefined data should not come.
Here I am getting data as well as some undefined data also. But I want to remove the undefined data.
Can anyone help me how to solve this problem
Thanks in advanced.

You use && for this, so when first condition is undefined the && operation will not go further and will render nothing else it will render the second part.
json_data.map((val, i)=>(
<>
{
val['big_egg'] &&
<div className="innerDiv">
<p align="left">Big Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.big_egg+"/-"}<button>ADD</button></p>
</div>
}
{
val['desi_egg'] &&
<div className="innerDiv">
<p align="left">Small Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.desi_egg+"/-"}<button>ADD</button></p>
</div>
}
{
val['small_egg'] &&
<div className="innerDiv">
<p align="left">Desi Egg</p>
<p align="left">weight: 500gm.</p>
<p align="left">{"₹"+val.small_egg+"/-"}<button>ADD</button></p>
</div>
}
</>
))

Related

how to display items with category name as title

hi I have multiple items with different categories. I want to display all item with its Category name as a title at header. My code displaying each item but category Title repeats with each item.
I want Category title only one time at the top and then its items list.
MY Code is this
{
formsList.map((item, index,temp=0) => {
if(temp!==item.cat_id)
{
temp = item?.cat_id;
return (
<div className="custom-control custom-radio mb-3">
<div className="form-control-label"> {item.category_title}</div>
<input
className="custom-control-input"
id= {item.id}
name= {item.cat_id}
type="radio"
/>
<label className="custom-control-label" htmlFor={item.id}>
{item.form_title} {temp}
</label>
</div>
)
}
return (
<div className="custom-control custom-radio mb-3">
<input
className="custom-control-input"
id= {item.id}
name= {item.cat_id}
type="radio"
/>
<label className="custom-control-label" htmlFor={item.id}>
{item.form_title}
</label>
</div>
)
})
}
My Json array is like this.
{"forms":
[
{"id":1,"category_title":"Individual Tax Return","cat_id":1,
"form_title":"Single},
{"id":2,"category_title":"Individual Tax Return","cat_id":1,
"form_title":"Married Filing Separately"},
{"id":3,"category_title":"Business Type", "cat_id":2,
"form_title":"SoleProprietorships"},
{"id":4,"category_title":"Business Type","cat_id":2,
"form_title":" Partnership"}
]
}
I want to display this one like as below
//////////////////
Individual Tax Return
Single
Married Filing Separately
Business Type
SoleProprietorships
Partnership
/////////////////////////
Please check and help with thanks
Please try this
json part
const recipes = [{
id: 716429,
title: "Pasta with Garlic, Scallions, Cauliflower & Breadcrumbs",
image: "http://ovuets.com/uploads/716429-312x231.jpg>",
dishTypes: [
"lunch",
"main course",
"main dish",
"dinner"
],
recipe: {
// recipe data
}
}]
function part
export default function Recipes() {
return (
<div>
{recipes.map((recipe) => {
return <div key={recipe.id}>
<h1>{recipe.title}</h1>
<img src={recipe.image} alt="recipe image" />
{recipe.dishTypes.map((type, index) => {
return <span key={index}>{type}</span>
})}
</div>
})}
</div>
)}

Disable all checkboxes except "checked" react hooks

I have listing of products and user can compare upto 4 products, when user checked 4 products I want to disable all checkboxes so user cannot select other product for compare until unless it uncheck one of 4 checkboxes.
const [checkedddItems, setCheckedItems] = useState({checkedItems : {}})
const handleComparePackage = (e, packageId) => {
const { id, checked } = e.target;
const updatedCheckedItems = comparedPackages.includes(packageId)? { [id]: checked } : {checkedddItems, [id] : checked }
console.log(updatedCheckedItems);
setCheckedItems({checkedItems: updatedCheckedItems})
}
{ insurancePackages.map((insPackage) => {
return (
<div className="col-lg-3 col-md-4 col-sm-6" key={insPackage.id}>
<div className="insurance-card active">
{compareSwitch &&
<div className="form-check">
<input
className="form-check-input"
type="checkbox"
id={insPackage.id}
checked={checkedddItems[insPackage.id]}
disabled={!checkedddItems[insPackage.id]}
onChange={(e) => { handleComparePackage(e, insPackage.id) }} />
</div>
}
<div className="thumb">
<img src="/insurance/logo.svg" alt="logo" />
</div>
<div className="title">
{insPackage.company.name}
</div>
<div className="text-detail">
{insPackage.description}
<br />
<Link href="/">
<a>View Package Details</a>
</Link>
</div>
</div>
)
})
}
From what I can tell, it seems like you need some way to disable all checkboxes when the following conditions are met:
the checkbox is not checked,
the amount of total checked items > 3
This should simply turn into a simple boolean statement in the disabled attribute on the checkbox <input/>.
<input
className="form-check-input"
type="checkbox"
id={insPackage.id}
checked={checkedddItems[insPackage.id]}
disabled={!checkedddItems[insPackage.id] && checkedddItems.length > 3} // right here
onChange={(e) => { handleComparePackage(e, insPackage.id) }} />

Linting in React

I am learning React.js. I am developing an app. My code is like below
<div className="ui pagination menu">
<span
className={
this.props.page === 1
? 'disabled item pagination'
: 'item pagination'
}
onClick={() => {
if (this.props.page === 1) {
return false;
}
this.pagination(this.props.page - 1);
}}
>
❮
</span>
<div className="item">
Page {this.props.page} of {this.props.maxPages}
</div>
<span
className={
this.props.page === this.props.maxPages
? 'disabled item pagination'
: 'item pagination'
}
onClick={() => {
if (this.props.page === this.props.maxPages) {
return false;
}
this.pagination(this.props.page+1);
<h1 className="ui attached warning message table"> // Line 185
<span id="address">Addresses</span>
<span id="user_details">
Welcome, <b> { this.state.userName } </b> |
<span id="logout" onClick={this.logout}> Logout </span>
<button className="ui teal button" onClick={this.openPopup}> <i className="plus square icon" />
Add Address
</button>
</span>
</h1>
{this.props.addresses.length > 0 ? (
I am getting Warning like below
Line 185: Expected an assignment or function call and instead saw an expression no-unused-expressions
Could anyone say how can I solve the Warning ?
I think you have missed closing of onClick function before your line 185, you should do this,
<span
className={
this.props.page === this.props.maxPages
? 'disabled item pagination'
: 'item pagination'
}
onClick={() => {
if (this.props.page === this.props.maxPages) {
return false;
}
this.pagination(this.props.page+1);
}} //This is missing
> //closing of span is also missing
<h1 className="ui attached warning message table"> // line 185
I believe you are missing the closing statement for the onClick. It may be helpful to use and IDE and install prettier. This will help you see where you are missing syntax. Additionally, here is more information on the rational for the error:
http://linterrors.com/js/expected-an-assignment-or-function-call

console.log to props breaks when used with its iteration using .map in render method

I have an object I received from a parent component as props. In render method, when printed with console.log prints me the complete object but it prints empty when the same object is being iterated using.map for html tags to print the values.
Cannot understand why this behavior, this is an extension from the question the complete object is available in that question, below is the part of object which is being iterated:
"mlaList": [{
"mlaNo": 92,
"lesseeId": 108,
"executionDate": "27/01/2017",
"signatoryInfo": "Test",
"overdueRate": 3.44,
"nonPaymentDays": 2,
"consolidationTerm": "Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "tooot#gmail.com",
"leaseMlaNo": "OPM1",
"statusDescription": "APPROVED"
}, {
"mlaNo": 93,
"lesseeId": 108,
"executionDate": "03/01/2017",
"signatoryInfo": "tess",
"overdueRate": 5.77,
"nonPaymentDays": 2,
"consolidationTerm": "Bi-Monthly",
"createdBy": null,
"createdDtm": null,
"updatedBy": null,
"updatedDtm": null,
"statusIndicator": null,
"signatoryEmail": "xyz#gmail.com",
"leaseMlaNo": "OPM2",
"statusDescription": "APPROVED"
}]
below is the component in which render method is also available with the mentioned code:
class AddLesseeInfoMLA extends Component {
constructor(props) {
super(props)
this.handlePrev = this.handlePrev.bind(this)
this.handleNext = this.handleNext.bind(this)
}
handlePrev() {
this.props.changeNavFunction(this.props.prevStep)
}
handleNext() {
this.props.changeNavFunction(this.props.nextStep)
}
render() {
console.log("Result::"+this.props.data)
return (
<div id="add-facility-info-profile-form-wrapper">
<Validation.components.Form id="add-facility-terms-info-form" ref="form" className="melody-common-form">
<div id="add-facility-terms-info-form">
{this.props.data.mlaList.map((data, index) =>
<div className="add-facility-terms-info-form-wrapper2" key={index}>
<div className="inputContainer melody-common-form-label">
<label className={index === 0 ? '' : 'melody-common-display-none'}>Lease MLA Number</label>
<Validation.components.Input value={data.leaseMlaNo} id="leaseMlaNo" className="short melody-common-input-disabled" type="text" name="leaseMlaNo" ref="leaseMlaNo" disabled="true" />
</div>
<div className="inputContainer melody-common-form-label">
<label className={index === 0 ? '' : 'melody-common-display-none'}>Status</label>
<Validation.components.Input value={data.statusDescription} id="statusDescription" className="short melody-common-input-disabled" type="text" name="statusDescription" ref="statusDescription" disabled="true" />
</div>
<div className="inputContainer melody-common-form-label">
<label className={index === 0 ? '' : 'melody-common-display-none'}>Consolidation Term</label>
<Validation.components.Input value={data.consolidationTerm} id="consolidationTerm" className="short melody-common-input-disabled" type="text" name="consolidationTerm" ref="consolidationTerm" disabled="true" />
</div>
<div className="inputContainer melody-common-form-label">
<label className={index === 0 ? '' : 'melody-common-display-none'}>Overdue Rate (%)</label>
<Validation.components.Input value={dataFormatter.toPercentFormat(data.overdueRate)} id="overdueRate" className="short melody-common-input-disabled" type="text" name="overdueRate" ref="overdueRate" disabled="true" />
</div>
<div className="inputContainer melody-common-form-label">
<label className={index === 0 ? '' : 'melody-common-display-none'}>Non Payment Days</label>
<Validation.components.Input value={data.nonPaymentDays} id="nonPaymentDays" className="short melody-common-input-disabled" type="text" name="nonPaymentDays" ref="nonPaymentDays" disabled="true" />
</div>
</div>
)}
</div>
</Validation.components.Form>
</div>
)
}
}
export default AddLesseeInfoMLA

How to iterate images on React?

Well, the question is very self-explanatory. I have this code here (inside a render, of course):
const images = [('http://placehold.it/100x100/76BD22'), ('http://placehold.it/100x100/76BD23')];
// ProductPage Views
const ProductPageView =
<section className="page-section ps-product-intro">
<div className="container">
<div className="product-intro">
<div className="product-intro__images">
<div className="product-gallery">
<ul className="product-gallery-thumbs__list">
{images.map(function(image, imageIndex){
return <li key={ imageIndex }>{image}</li>;
})}
</ul>
</div>
</div>
</div>
</div>
</section>
The thing is I don't know how to iterate those images on the array. What's wrong with my code?
Your array is an array of image URLs, not image tags. So your code is close but you need to put the image inside of an image tag inside of your list item tag.
const images = [('http://placehold.it/100x100/76BD22'), ('http://placehold.it/100x100/76BD23')];
// ProductPage Views
const ProductPageView =
<section className="page-section ps-product-intro">
<div className="container">
<div className="product-intro">
<div className="product-intro__images">
<div className="product-gallery">
<ul className="product-gallery-thumbs__list">
{images.map(function(imageSrc) {
return (
<li key={ imgSrc }>
<img src={ imgSrc } />
</li>
);
})}
</ul>
</div>
</div>
</div>
</div>
</section>
I would also recommend against using an array index as a key in general. The imgSrc is unique so it would make a good key here.
Also, make sure to include an alt attribute on the img for screen readers. You might want to make your array like this:
const images = [
{ src: 'http://placehold.it/100x100/76BD22', alt: 'Your description here 1' },
{ src: 'http://placehold.it/100x100/76BD23', alt: 'Your description here 2' }
];
// ...
{images.map(function(imageProps) {
return (
<li key={ imageProps.src }>
<img src={ imageProps.src } alt={ imageProps.alt } />
</li>
);
})}
I assume you want to display them as images, right? You should use img tag then.
<ul className="product-gallery-thumbs__list">
{images.map(function(image, imageIndex){
return <img key={ imageIndex } src={ image } />
})}
</ul>

Resources