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
Related
I receive an array like this from backend:
[
{
id: 0,
name: "John",
language: "Enlgish"
},
{
id: 1,
name: "Chris",
language: "Spanish"
},
{
id: 2,
name: "Bastian",
language: "German"
}
]
So I display the languages from this array in a table, and to do that I map through them.
I don't want to show the first language on the first object of this array
Parent.js
const [language, setLanguage] = useState ([])
useEffect(() => {
axios
.get('api').then((res) => {setLanguage(response.data.languages)})
}, [])
Child.js
return(
{language.map((lang, i) => {
return (
<tr key={"item-" + i}>
<td>
<div>
<input
type="text"
value={
lang.language
? lang.language.shift()
: lang.language
}
</div>
</td>
</tr>
))}
)
So what I have tried by far is the shift method which removes the first item of an array, but it didn't work.
This error happened :TypeError: lang.language.shift is not a function
How can I fix this?
Use the index
{language.map((lang, i) => {
(i > 0) && (
return (
......
Im trying to make a navigation bar for a website and it's giving me the "Warning: Each child in a list should have a unique "key" prop." inside my props.dropList.map
I have two files:
NavigationItems.js -> where I render my navigation bar
const NavigationItems = () => {
const projectDropdown = [
{ id: 0, value: "architecture" },
{ id: 1, value: "land" },
{ id: 2, value: "design" },
{ id: 3, value: "list" },
];
const officeDropdown = [
{ id: 4, value: "contact" },
{ id: 5, value: "team" },
];
return (
<div>
<ul className={styles.NavigationItems}>
<NavigationItem
link={`/projects`}
name="projects"
dropList={projectDropdown}
/>
<NavigationItem link={`/news`} name="news" exact />
<NavigationItem
link={`/office`}
name="office"
dropList={officeDropdown}
/>
</ul>
</div>
);
};
export default NavigationItems;
NavigationItem.js -> where I use the map function
const NavigationItem = (props) => {
let i = 0;
return (
<li className={styles.NavigationItem}>
<NavLink to={props.link} activeClassName={styles.active}>
{props.name}
</NavLink>
{props.dropList && (
<div className={styles.DropdownItems}>
<ul className={styles.DropdownItem}>
{props.dropList.map((drop) => {
console.log("i " + i);
console.log("id " + drop.id);
console.log("value " + drop.value);
i++;
return (
<li key={drop.id}>
<NavLink
exact
to={`${props.link}/${drop.value}`}
activeClassName={styles.active}
>
{drop.value}
</NavLink>
</li>
);
})}
</ul>
</div>
)}
</li>
);
};
export default NavigationItem;
So what happens is that the code loops twice duplicating the key values. It should be looping only once. I don't know why it loops twice, I'm only mapping my values once. For reference
this is what my console shows when I click my links
So your problem doesn't occure in either of the components you provided, but in your "Land" component. (Check the render method of Land)
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.
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>
);
};
I have doubt I'm doing it right when returning a component in a map iteration. How can I improve the code or is there any better way to do it? (although my code is working)
https://codesandbox.io/s/5yzqy6vyqx
Parent
function App() {
return (
<div className="App">
{[
{
name: "banana",
count: 3
},
{
name: "apple",
count: 5
}
].map(({ name, count }) => {
return <List name={name} count={count} />;
})}
</div>
);
}
List component
const List = ({ name, count }) => {
return (
<li>
{name}: {count}
</li>
);
};
Simplify like this.
function App() {
return (
<div className="App">
<ul>
{[
{
name: "banana",
count: 3
},
{
name: "apple",
count: 5
}
].map(({ name, count }) => <li>{name}:{count} </li>)}
</ul>
</div>
);
}
You need to set unique value as key to List component because you are rendering List in loop. Unique value can be id per each object in array or index from .map but we are recommended to have unique id per object in data and use that as key when we iterate.
Index is not recommended as key but in worst case we can.
Also add ul element so that li will be rendered under ul
Below code has improved with adding key, ul and .map function without return
function App() {
return (
<div className="App">
<ul>
{[
{
id: 1
name: "banana",
count: 3
},
{
id:2,
name: "apple",
count: 5
}
].map(({ id, name, count }) => (
<List key={id} name={name} count={count} />;
))}
</ul>
</div>
);
}