Nested Map is not working properly on react template - javascript

I am trying to mapping through three objects in react to render multiple categories on react template , Code doesn't give any error but its not showing any content on react web page.
return (
<div className="container pt-80">
<center>Category Grouping</center>
{categories.map((cate,key)=>{
subCategories.map(subCate=>{
if(subCate.category === cate.id){
pType.map(ptype=>{
if (ptype.category === subCate.id){
console.log("Category : ",cate.category)
console.log("Sub Category : ",subCate.subCatName)
console.log("Product Type : ",ptype.ptype)
console.log("*******************************************")
return(
<Fragment>
<h1 style={{marginLeft:"30px"}}>{cate.category}</h1>
<h1 style={{marginLeft:"60px"}}>{subCate.subCatName}</h1>
<h1 style={{marginLeft:"120px"}}>{ptype.ptype}</h1>
</Fragment>
)
}
})
}
})
})}
</div>
)
Its printing the correct values in console :

Extending what #Akhil said in the comment. You are actually not returning anything in you're first two map calls, only the last.
add return before both nested map calls:
return subCategories.map(subCate=>{...
and
return pType.map(ptype=>{
Also I would add a return null after your if statements. Map expects a return value.
if(subCate.category === cate.id){
....
}
return null;
and
if (ptype.category === subCate.id){
....
}
return null;

Look into the comment by #Akhil. You missed the return for the map.
const categories = [{ id: 1, category: "Foods & Supplements" }];
const subCategories = [{ id: 1, category: 1, subCatName: "Herbal Drinks" }];
const pType = [
{ id: 1, category: 1, ptype: "Herbal Juice" },
{ id: 2, category: 1, ptype: "Herbal Coffee Tea&Soup" }
];
export default function App() {
return (
<div>
<h1>Category Grouping</h1>
{categories.map((cate, key) => (
<div key={key}>
{subCategories.map((subCate, sKey) => (
<div key={sKey}>
{subCate.category === cate.id &&
pType.map((ptype, pKey) => (
<div key={pKey}>
{ptype.category === subCate.id && (
<>
<h1 style={{ marginLeft: "30px" }}>{cate.category}</h1>
<h1 style={{ marginLeft: "60px" }}>
{subCate.subCatName}
</h1>
<h1 style={{ marginLeft: "120px" }}>{ptype.ptype}</h1>
</>
)}
</div>
))}
</div>
))}
</div>
))}
</div>
);
}
Also, use some sort of linting (e.g. Eslint) and format the code, both will help to catch syntax errors.

Related

How to display array data that varies in length

I got 2 objects inside the array, and 1st object is longer than the 2nd object. How can i render all of the properties of the 1st object without getting undefined, i get undefined because there are only 2 properties existing in the second object of the array .Also how can i calculate total sum of exercises?
function App() {
const course = [
{
name: 'Half Stack application development',
id: 1,
parts: [
{
name: 'Fundamentals of React',
exercises: 10,
id: 1
},
{
name: 'Using props to pass data',
exercises: 7,
id: 2
},
{
name: 'State of a component',
exercises: 14,
id: 3
},
{
name: 'Redux',
exercises: 11,
id: 4
}
]
},
{
name: 'Node.js',
id: 2,
parts: [
{
name: 'Routing',
exercises: 3,
id: 1
},
{
name: 'Middlewares',
exercises: 7,
id: 2
}
]
}
]
// calculate total of exercises
const totalExercises = course.reduce((total, course) => total + course.exercises, 0);
return (
<div className="App">
<header className="App-header">
<h1>Seoul</h1>
<Course course={course} totalExercises={totalExercises} />
</header>
</div>
)
}
function Course({ course, totalExercises }) {
return (
<>
<ul>
{course.map((course) => (
<li key={course.id}>
<p>{course.name} {course.exercises}</p>
<p>{course.parts[0].name}</p>
<p>Total exercises: {course.parts[0].exercises},</p>
<p>{course.parts[1].name}</p>
<p>Total exercises: {course.parts[1].exercises}</p>
// Undefined one below
UNDEFINED <p>{course[0].parts[2].name}</p>
</li>
))}
</ul>
</>
);
}
You could use map the parts array to the elements:
function Course({ course, totalExercises }) {
return (
<>
<ul>
{course.map((course) => (
<li key={course.id}>
<p>{course.name} {course.exercises}</p>
{
course.parts.map((part, id)=>(
<React.Fragment key={id}
<p>{part.name}</p>
<p>Total Excercises: {part.exercises}</p>
</React.Fragment>
))
}
</li>
))}
</ul>
</>
);
}
If you are not sure that if a key is present in an object and want to render it if it is there without having any error, use ?. to access keys.
For example
let a ={name:'Shivansh'};
console.log(a?.name,a?.id);
a ={id:3};
console.log(a?.name,a?.id);
Output for 1st console.log
Shivansh undefined
2nd console.log
undefined 3
One more thing you can give a fallback customized text if you want instead of undefined by using ?? operator.
op1 ?? op2
if op1 gives undefined then op2 is executed
Ex->
console.log(a?.name??'',a?.id??'')
//This will ensure you don't receive undefined but empty string.
To calculate total sum of excercies->
let sum = 0;
course.forEach(course => course ? .parts ? .forEach(part => sum = sum + p
parseInt(part ? .exercises ? ? 0)))
function Course({ course, totalExercises }) {
return (
<>
<ul>
{course.map((course) => (
<li key={course.id}>
<p>{course.name} {course.exercises}</p>
{course.parts.map((part,i) => {
return(
<div key={i}>
<p>{part.name}</p>
<p>Total exercises: {part.exercises},</p>
</div>
)
})}
</li>
))}
</ul>
</>
);
}
Same way that you are mapping course.map(... you can then map the parts for each course, code above works without an error for me.
You try to render an array manually... it's a bad idea imagine that your array is dynamic how you can anticipate the number of elements in the array?
Done as follows.
function Course({ course, totalExercises }) {
return (
<>
<ul>
{course.map((course) => (
<li key={course.id}>
<p>{course.name} {course.exercises}</p>
{course.parts?.map((part, index) => (
<div key={index}>
<p>{part.name}</p>
<p>Total exercises: {part.exercises},</p>
</div>
))}
</li>
))}
</ul>
</>
);
}
I hope my English doesn't tire you, I'm French-speaking

How can I bold text within an object array items string?

I am using the data from below to pass as props in React. Everything works fine but I need to only bold the words "target audience" in the text property. Is there a way to do this?
const SlideData = [
{
index: 1,
title: "Target Audience",
text: [
"The target audience for this course is anyone who is assigned roles as a HR Employee Maintainer...",
],
image: {
src: targetAudience,
width: imageSize,
},
},
index: 2,
title: "Reporting ",
text: [
"Reporting Manager is designated to...",
],
image: {
src: reporting,
width: imageSize,
},
},
]
export default SlideData
Added Render Component
const TextSlide = ({ title, text = [], list, image }) => {
return (
<>
<div className="slide">
<div className="standard-grid">
<span className="slide-title title">{title}</span>
<div className="content">
{text.map((t, i) => (
<p key={i} className="text">
{t}
</p>
))}
</div>
{image ? <img className="picture" src={image.src} style={{ maxWidth: image.width }} alt="image" /> : null}
</div>
</div>
</>
);
};
export default TextSlide;
``
You could split the text by target audience, and map the chunks inbetween to text nodes appending a node to each element:
"The target audience for this course is anyone who is assigned roles as a HR Employee Maintainer...",
.split("target audience")
.map((text, index) => <>{index !== 0 && <b>target audience</b>} {text}</>)
A more sophisticated approach would be to inject html tags into the text, and use dangerouslySetInnerHTML:
const formatted = text.replace(/(target audience)/g, it => `<b>${it}</b>`);
return <div dangerouslySetInnerHTML={formatted} />;
You could change the text to an object with a key of __html and use bold tags to render it by using dangerouslySetInnerHTML:
const SlideData = [
{
index: 1,
title: "Target Audience",
text: [
{
__html:
"The <b>target audience<b> for this course is anyone who is assigned roles as a HR Employee Maintainer...",
},
],
image: {
src: targetAudience,
width: imageSize,
},
},
];
const TextSlide = ({ title, text = [], list, image }) => {
return (
<>
<div className="slide">
<div className="standard-grid">
<span className="slide-title title">{title}</span>
<div className="content">
{text.map((t, i) => (
<p key={i} className="text" dangerouslySetInnerHTML={t} />
))}
</div>
{image ? (
<img
className="picture"
src={image.src}
style={{ maxWidth: image.width }}
alt="image"
/>
) : null}
</div>
</div>
</>
);
};
Here is a small codepen for demonstration.
Try this:
text: ["The ", <strong>target audience</strong>, " for this course is anyone who is assigned roles as a HR Employee Maintainer..."]
React will render this as a string with the HTML tags applied.

showing only first element from data

Hi all I have following code: my code
In this scenario I am receiving some data from backend
const attachments = [
{
id: 1,
name: "someURLL_Name_1",
link: "https://someURLL_Name_1",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
},
{
id: 2,
name: "someURLL_Name_2",
link: "https://someURLL_Name_2",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
},
{
id: 3,
name: "someURL_Name_3",
link: "https://someURLL_Name_3",
img: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg"
}
];
I need to map them all and show only first element form my data, and show with numbers rest hided data.
In the end it should be like something like this:
someURL_Name_1 https://someURLL_Name_1 +2 more
I successfully mapped all my data and write little logic for + more.
<div className={Styles.attachments}>
{data.map((item) => {
return <Attachment key={item.id} data={item} image={item.img} />;
})}
{data.length > 1 && (
<span className={Styles.more}>+{data.length - 1} more</span>
)}
</div>
Please help me to resolve a problem. Again, I want to show only first element , and then if there are another elements then I should hide them and show hide elements with numbers.
Thanks.
Just don't map over all entries then. The following will work :-
export const Attachments = ({ data }) => {
return (
<div className={Styles.attachments}>
{data[0] && (
<Attachment key={data[0].id} data={data[0]} image={data[0].img} />
)}
{data.length > 1 && (
<span className={Styles.more}>+{data.length - 1} more</span>
)}
</div>
);
};

Iterating a array data reactjs

const rowData = this.state.market.map((market) => {
console.log("details", market["info"])
{
return {
marketInfo: (
<div>
{market && !!market["info"] ? (
<div>
<p>{market["info"]["name"]}</p>
</div>
) : null}
</div>
),
place: "place",
area: "area",
action: "action",
};
}
});
I am iterating an array in marketInfo, but I am getting the same name whenever i m iterating, but in console log I am getting different names. Whats actually wrong with my code! can anyone help me with it!
const rowData = this.state.market.map((market) => {
console.log("details", market["info"])
return {
marketInfo: (
<div>
{market?.["info"] ? (
<div>
<p>{market["info"]?.["name"] || ""}</p>
</div>
) : null}
</div>
),
place: "place",
area: "area",
action: "action",
};
});
try this code.
I think you forgot to return an object in your map func

How can I render the nested data in ReactJS?

I have the bellow alike data, and I would like to render them.
Let's say I would like to display firstName, address, and seatType and flightId for each flight the passenger has.This has to be done for each passenger. How can I achieve that?
Updated
[
{
"id": 1,
"firstName": "Smith",
"lastName": "John",
"address": [
"1 Street",
"YYY",
],
"flights": [
{
"flightId": 1,
"seatType": "oridinary"
},
{
}
]
},
{},
]
Here is my code
render() {
const { data } = this.state;
return (
<div>
{" "}
{Object.keys(data).map((key, index) => (
<p key={index}>
{" "}
{key} {data[key].flights}
{data[key].flights.map(k => (
{data[key].flights[k]}
))}
</p>
))}
</div>
);
}
I'm assuming you're looking for something like this:
return (
<div>
{
passengers.map(passenger => {
if (!passenger.id) { return null } /* + */
return (
<div key={passenger.id}>
<span>{passenger.firstName} {passenger.lastName}</span>
<div>
<span>Passenger's Flights</span>
{
passenger.flights && /* + */
Array.isArray(passenger.flights) && /* + */ passenger.flights.map(flight => {
if (flight.flightId) {
return (
<div key={flight.flightId}>
{flight.seatType}
</div>
)
}
return null
})
}
</div>
</div>
)
})
}
</div>
);
}
Note: remember that you should not use index as a key.
Edit: You need to add a null/undefined check
render() {
const { data } = this.state;
return (
<div>
{data.map((passenger, index) => (
<p key={index}>
{passenger.firstName} {passenger.address.join(' ')}
{passenger.flights.map(flight => (
<p>{flight.seatType} {flight.flightId}</p>
))}
</p>
))}
</div>
);
}
render() {
const { data } = this.state;
return (
<div>
{data.map(({id, firstName, address, flights}) => (
<p key={id}>
<div>{firstName}</div>
<div>{address.join(', ')}</div>
{flights.map(f => (<div key={f.flightId}>{f.flightId}-{f.seatType}</div>))}
</p>
))}
</div>
);
}
Not sure if it compiles but it's something like this. Also, if you have an ID, use it as key.

Categories