Display array value with multiple objects - javascript

I need to display the values in my UsersData array, same as array numbers, but I can not do that in ReactJS.
Here's an example available in CodeSandbox.
https://codesandbox.io/s/n08n2m7mpj
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const usersData = [
{
total: 3,
data: [
{ id: 1, name: "Tania", username: "floppydiskette" },
{ id: 2, name: "Craig", username: "siliconeidolon" },
{ id: 3, name: "Ben", username: "benisphere" }
]
}
];
const numbers = [1, 2, 3, 4, 5];
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{numbers.map((number, index) => (
<li key={index}>{number}</li>
))}
{usersData.length > 0 ? (
usersData.map((data, index) => <div key={index}>Nome: {data.name}</div>)
) : (
<div>No users </div>
)}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1) usersData is an array containing one element (an object)
2) You need to iterate over the data array of that object and display the value of name property for each its objects.
{usersData[0].data.length > 0 ? (
usersData[0].data.map((obj, index) => <div key={index}>Nome: {obj.name}</div>)
) : (
<div>No users </div>
)}
Forked update

Your usersData is an array usersData=[] which contains an object usersData=[{}] which itself contains the array of data usersData=[{data: []}] so you need to change your variable to an object and use the map function on the array of data inside it like so
const usersData = {
total: 3,
data: [
{ id: 1, name: "Tania", username: "floppydiskette" },
{ id: 2, name: "Craig", username: "siliconeidolon" },
{ id: 3, name: "Ben", username: "benisphere" }
]
};
and your loop would become
{usersData.data.length > 0 ? (
usersData.data.map((user, index) => <div key={index}>Nome: {user.name}</div>)
) : (
<div>No users </div>
)}

You need to do
usersData[0].data.map(({name}, index) => <div key={index}>Nome: {name}</div>)
Becaise you are not accessing the data array in your code above

usersData.map((userData, index) => {
return userData.data.map(item => {
return <div key={index + item.id}>Nome: {item.name}</div>;
});
});

Related

how to map an array of objects that has values of array of objects

I have a list of comments that I fetch from my API looking like this. A comment has likes and dislikes alongside the user who posted the like or dislike.
const comments = [
{
id: 1,
comment: "nice",
author: "jenny",
likes: [
{
id: 1,
user: "alice"
},
{
id: 2,
user: "bob"
}
],
dislikes: [
{
id: 3,
user: "sam"
}
]
},
{
id: 2,
comment: "good job",
author: "alice",
likes: [
{
id: 2,
user: "bob"
}
],
dislikes: [
{
id: 3,
user: "sam"
}
]
}
]
Lets say Alice is logged in.
Now the map to display the comments works fine, but I want to do "nested map" which loops through the likes and dislikes array of objects within the same object array and see if the user of a like or dislike matches who is logged in to display a confirmation.
My current code:
const signedInUser = "alice";
return(
Object.keys(comments).map((x, index) => {
const com = comments[x];
<div className="comment" key={index}>
<p>{com.author}</p>
<p>{com.comment}</p>
{com.likes.map((x) => {
{
x.user === signedInUser ? (
<p>You liked this</p>
) : (
<button>Like</button>
);
}
})}
</div>;
})
);
I am doing this with react, since I am trying to
You are suppose to use some to get a boolean response if there exist a like by the same user.
map return response for every object in the like array.
return(
Object.keys(comments).map((x, index) => {
const com = comments[x];
<div className="comment" key={index}>
<p>{com.author}</p>
<p>{com.comment}</p>
{com.likes.some((x) => x.user === signedInUser)?
(
<p>You liked this</p>
) : (
<button>Like</button>
);
}
</div>;
})
);
const renderLikeOrDislikeButton = (arr, text1, ) =>{
if(arr.some((x) => x.user === signedInUser)){
return <p>You {text1} this</p>
}
return <button>{text2}</button>
}
return(
{
Object.keys(comments).map((x, index) => {
const com = comments[x];
return(
<div className="comment" key={index}>
<p>{com.author}</p>
<p>{com.comment}</p>
{renderLikeOrDislikeButton(com.likes, "liked", "Like")}
{renderLikeOrDislikeButton(com.likes, "disliked", "Dislike)}
</div>
)
});

Mapping an array of each object in array in React

I've got a data.json file with an array of group objects, and each group object contains products array, like:
[
{
"groupId": int
"familyId": int,
"products": array (lenght of 10-50)
}
{
"groupId": int
"familyId": int,
"products": array (lenght of 10-50)
}, and so on...
]
I would like to map them like:
<ul> GroupId
<li>Product 1</li>
<li>Product 2</li>
<ul/>
<ul>
GroupId
<li>Product 1</li>
<li>Product 2</li>
</ul>
etc.
I've tried to use foreach function and then map every array but it doesn't work.
import data from '../data.json';
let productsList = [];
{data.forEach((el) => {productsList.push(el.products)})}
{productsList.forEach((array) => {
array.map((el) => {
return (
<ul>
<li>{el.name}</li>
</ul>
)
})
})}
I recommend you solve this with simple react components, it will make your code more readable.
I created a simple example to solve your issue
export default function App() {
const data = [
{
groupId: 1,
familyId: 1,
products: [
{ id: 1, name: "product 1", price: 10 },
{ id: 2, name: "product 2", price: 20 }
]
},
{
groupId: 2,
familyId: 2,
products: [{ id: 3, name: "product 3", price: 30 }]
}
];
return (
<div className="App">
{data.map((group) => (
<ProductGroup group={group} />
))}
</div>
);
}
ProductGroup Component
const ProductGroup = ({ group }) => {
return (
<>
<ul>{group.groupId}</ul>
{group.products.map((product) => (
<ProductItem product={product} />
))}
</>
);
};
ProductItem Component
const ProductItem = ({ product }) => {
return (
<li>
<span>{product.name}</span>
<span style={{ marginLeft: "10px" }}>{product.price}$</span>
</li>
);
};
Try this one
const listItems = () => (
<>
{array.map((group) => (
<ul key={group.groupId}>
{group.groupId}
{group.products.map((productList, index) => (
<li key={index}>{productList}</li>
))}
</ul>
))}
</>
);

React JS. How can I display the image inside the object?

How can I display the image inside the object in React.js?
const Area = () =>{
const flags = [
{ id: 1, name: "USA", image: "./us.png" },
{ id: 2, name: "Canada", image: "./ca.png" },
];
return (
<div>
{flags.map((area) => {
return <img key={area.id} src={area.image} />;
})}
</div>
)}
The very first thing that you need to do is wrap the src in {} which you're doing already.
Then if you're using webpack. Instead of : <img src={"./us.png"} />
You need to use require() like this <img src={require('./us.png')} />
const Area = () => {
const flags = [
{ id: 1, name: "USA", image: "./us.png" },
{ id: 2, name: "Canada", image: "./ca.png" },
]
return (
<div>
{flags.map((area) => {
return <img key={area.id} src={require(area.image)} />;
})}
</div>
)}
}
Another option would be to first import the image as shown below
import ca from './us.png' or const us = require('./us.png).
Then add them to your flags object like shown below:
import usa from './us.png;
import canada from './ca.png;
const Area = () => {
const flags = [
{ id: 1, name: "USA", image: usa },
{ id: 2, name: "Canada", image: canada },
]
return (
<div>
{flags.map((area) => {
return <img key={area.id} src={area.image} />;
})}
</div>
)}
}
You can use require for images inside an object.But your code works fine even without that you just have to return it inside return method().
const Area = () =>{
const flags = [
{ id: 1, name: "USA", image: require('./us.png') },
{ id: 2, name: "Canada", image: require('./ca.png') },
]
return (
<div>
{flags.map((area) =>
<img key={area.id} src={area.image} />
)}
</div>
)
}
return(
Area()
)
It works fine this way as well
const Area = () =>{
const flags = [
{ id: 1, name: "USA", image: "./us.png" },
{ id: 2, name: "Canada", image: "./ca.png" },
]
return (
<div>
{flags.map((area) =>
<img key={area.id} src={area.image} />
)}
</div>
)
}
return(
Area()
)
As I mentioned in my comments that please double check the path of the image. Image path might be a problem else it is looking fine. Moreover, you can press ctrl+click on path to route to that folder or check it manually.

items are not draggable

I am using library called react-beautiful-dnd for draggable lists. The use case of my application is there will be a nested list which should be draggable and the items inside its corresponding list should also be draggable. The items from List1 should not be dragged to List2. For this I am trying to create draggable vertical list which is not working. The items are not draggable at all. I have created a sandbox of this either.
here it is
https://codesandbox.io/s/vqzx332zj7
The source code is
import DraggableSubItems from "./DraggableSubItems";
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const items = [
{
id: 1,
name: "Top Level",
path: "top-level",
children: [
{
id: 1,
name: "dropbox",
path: "dropbox"
},
{
id: 2,
name: "asana",
path: "asana"
}
]
},
{
id: 2,
name: "Frontend Library",
path: "frontend-library",
children: [
{
id: 1,
name: "reactjs",
path: "reactjs"
},
{
id: 2,
name: "vuejs",
path: "vuejs"
}
]
}
];
const grid = 8;
const getListStyle = () => ({
padding: grid,
display: "flex",
flexDirection: "column"
});
class DraggableItems extends React.Component {
constructor(props) {
super(props);
this.state = {
items
};
}
onDragEnd = result => {
console.log("drag", result);
// dropped outside the list
if (!result.destination) {
return null;
}
if (result.destination.index === result.source.index) {
return;
}
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
console.log("items", items);
this.setState({
items
});
};
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => {
console.log("provided", provided, snapshot);
return (
<div
ref={provided.innerRef}
style={getListStyle(snapshot.isDraggingOver)}
>
{this.state.items.map(item => (
<Draggable
key={item.id}
draggableId={item.id}
index={item.id}
>
{(draggableProvided, draggableSnapshot) => {
console.log(
"provided inside Draggable",
draggableProvided,
draggableSnapshot
);
return (
<React.Fragment>
<div
ref={draggableProvided.innerRef}
{...draggableProvided.draggableProps}
style={getListStyle(
draggableSnapshot.isDragging,
draggableProvided.draggableProps.style
)}
{...draggableProvided.dragHandleProps}
>
<h3>{item.name}</h3>
<DraggableSubItems
subitems={item.children ? item.children : []}
type={item.id}
/>
</div>
{draggableProvided.placeholder}
</React.Fragment>
);
}}
</Draggable>
))}
</div>
);
}}
</Droppable>
</DragDropContext>
);
}
}
export default DraggableItems;

React/React-Router - TypeError: Cannot read property of undefined

I'm a React novice, trying my hand at creating my first application. I've been trying to keep it super simple so far whilst following some tutorials and documentation.
The below code is causing a TypeError as shown in the image here
error screenshot
Here is my code:
import React from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const App = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/hospitals">Find a Patient</Link></li>
</ul>
<hr/>
<Route exact path="/" component={Home}/>
<Route path="/hospitals" component={Hospitals}/>
</div>
</Router>
)
const Home = () => (
<div>
<h2>Home</h2>
</div>
)
const HOSPITALS = [
{ id: 0, name: 'St James', patients: [
{ id: 1, location: 'Maple ward' },
{ id: 2, location: 'Birch ward' },
{ id: 3, location: 'Pine ward' }
]},
{ id: 1, name: 'Harrogate Hospital', patients: [
{ id: 4, location: 'Sycamore ward' },
{ id: 5, location: 'Fern ward' },
{ id: 6, location: 'Oak ward' }
]},
{ id: 2, name: 'Leeds General Infirmary', patients: [
{ id: 7, location: 'Trout ward' },
{ id: 8, location: 'Eel ward' },
{ id: 9, location: 'Salmon ward' }
]}
]
const find = (id) => HOSPITALS.find(p => p.id === id)
const Hospitals = ( {match} ) => {
let hospitals = HOSPITALS.map((hospital) => {
return (
<li key={hospital.id}>
<Link to={`${match.url}/${hospital.id}/patients`} >
{hospital.name}
</Link>
</li>
)
});
return (
<div>
<h2>Hospitals</h2>
<ul>
{hospitals}
</ul>
<hr/>
<Route path={`${match.url}/:hospitalID/patients`} component={Patients}/>
</div>
)
}
const Patients = ( {match} ) => {
const hospitalArray = find(match.params.hospitalID)
let patients = hospitalArray.patients.map((patient) => {
return (
<li key={patient.id}>
<Link to={`${match.url}/${patient.id}`} >
{patient.location}
</Link>
</li>
)
});
return (
<div>
<h2>Patient for {match.params.hospitalID}</h2>
<ul>
{patients}
</ul>
<hr/>
<Route path={`${match.url}/:patientID`} component={PatientDetail}/>
</div>
)
}
const PatientDetail = ({match}) => (
<div>
<h2>Patient details for {match.params.patientID}</h2>
</div>
)
export default App;
Any help or insights would be much appreciated.
Thanks!

Categories

Resources