I can't display selected item image only alt are in display.
App.js
<Route path="/Item/:id" element={<Item />} />
This is my MUI styled Link Trending.js
<StyledLink to={"/Item/" item._id}>
<Stack>
<ItemName>{item.name}</ItemName>
<Typography>Brand: {item.brand}</Typography>
</Stack>
</StyledLink>
This is my Item.js I can display the item.name and item.brands but I can't display image only alts
import { useParams } from "react-router-dom";
import items from "../../items";
const Item = () => {
let { id } = useParams();
const item = items.find((item) => item._id === id);
console.log(item);
return (
<>
<Stack sx={{ backgroundColor: "skyblue", height: "900px" }}>
<Stack>
<Stack sx={{ width: "250px", height: "400px" }}>
<img src={item.image} alt={item.brand} loading="lazy" />
</Stack>
</Stack>
<Stack>{item.price}</Stack>
</Stack>
</>
);
};
export default Item;
This is the results of my console.log and element
{_id: '2', name: 'Headset', image: './images/headset3.jpg', description: 'Noise Cancelling Headset', brand: 'Hyper', …}
brand: "Hyper"
category: "Computer"
countInStock: 1030
description: "Noise Cancelling Headset"
image: "./images/headset3.jpg"
name: "Headset"
numReviews: 169
preSalePrice: 96
price: 98.6
rating: 4.5
_id: "2"
[[Prototype]]: Object
this is my items.js
const items = [
{
_id: "1",
name: "Keyboard",
image: "./images/keyboard2.jpg",
description: "High-Tech Keyboard",
brand: "Monster",
category: "Computer",
price: 300,
preSalePrice: 300,
countInStock: 688,
rating: 4,
numReviews: 100,
},
{
_id: "2",
name: "Headset",
image: "./images/headset3.jpg",
description: "Noise Cancelling Headset",
brand: "Hyper",
category: "Computer",
price: 98.6,
preSalePrice: 96,
countInStock: 1030,
rating: 4.5,
numReviews: 169,
},
];
export default items;
and this the result I got I don't know what's going on here. I also change width and height of img but nothing happen. Thank you
CodePudding user response:
You need to import the images before you can use them.
In your items
file, you'll need to import them like so and add the result of the import to each item in the array:
import HeadSet from './images/headset3.jpg'
// stuff
[
// modify each item in array to do same
{
_id: "2",
name: "Headset",
image: HeadSet,
description: "Noise Cancelling Headset",
brand: "Hyper",
category: "Computer",
price: 98.6,
preSalePrice: 96,
countInStock: 1030,
rating: 4.5,
numReviews: 169,
},
]
CodePudding user response:
But it works using .map() in Trending.Js
import items from "../../items";
<StackImages direction="row">
{items.map((item) => (
<StackImg key={item._id}>
<img src={item.image} alt={item.name} />
<StyledLink to={"/Item/" item._id}>
<Stack>
<ItemName>{item.name}</ItemName>
<Typography>Brand: {item.brand}</Typography>
</Stack>
</StyledLink>
</StackImg>
))}
{/* End of Image List */}
</StackImages>
This is the result in Trending.js its working .Map() array
but if I select item it will redirect to Item.js and Im using .find() id to display item..