I'm trying to render a Card component dynamically mapped from an array of objects.
The issue is I'm getting an "unexpected token error ..." And URL won't render. I should see five cards display based on the data inside the array, but it throws an error. Does anyone see where I'm going wrong? I'm using React 18 if that matters.
Component code:
import React from "react";
import links from "../links";
function Card (props) {
return (
<div>
<div className="link-container">
<div className="row">
<div className="card">
<hr className="divide"></hr>
<img className="img" src={props.img} alt="social-icon" />
<h4>{props.name}</h4>
</div>
</div>
</div>
</div>
)
}
Data:
const links = [
{
id: 1,
name: "Youtube",
img:"./img/youtube.svg",
href: "https://www.youtube.com/c/SubwaySounds"
},
{
id: 2,
name: "Spotify",
img:"./img/spotify.svg",
href: "https://artists.spotify.com/c/artist/3DM32kjsG7Pp5EM7o3Uv7t/profile/overview"
},
{
id: 3,
name: "Tiktok",
img:"./img/tiktok.svg",
href: "https://www.tiktok.com/#nysubwaysounds"
},
{
id: 4,
name: "Instagram",
img:"./img/instagram.svg",
href: "https://www.instagram.com/nycsubwaysounds/?hl=en"
},
{
id: 5,
name: "Shop",
img:"./img/shop.svg",
href: "https://my-store-11524143.creator-spring.com/"
}
]
export default links;
App.jsx:
import Header from "./Header";
import Card from "./Card";
import links from "../links";
function CreateCard (socialLinks) {
return (
<Cards
key= {socialLinks.id}
img= {socialLinks.img}
name= {socialLinks.name}
href= {socialLinks.href}
/>
)
}
function App() {
return (
<div>
<Header />
<Card {links.map(createCard)} />
</div>
);
}
export default App;
use the React map method
function App() {
return (
<div>
<Header />
{
links.map((link, linkKey) => (
<Card
key={linkKey}
img= {socialLinks.img}
name= {socialLinks.name}
href= {socialLinks.href}
/>
))
}
</div>
);
}
Related
My image is not showing in React app. I am trying to fetch the path from JSON and pass the path using props in <img> tag.
Example JSON object with the product data:
let data = [
{
id: 1,
name: "Striped Slim Fit Shirt",
image: "./Assets/m1.jpg",
price: 1000,
category: "Men",
size: "XL",
inStock: true,
},
{
id: 2,
name: "Full Sleeves Slim Fit Shirt",
image: "./Assets/m2.jpg",
price: 2000,
category: "Men",
size: "L",
inStock: true,
},
];
export default data;
My parent component from which I am passing props.
import { Fragment } from "react";
import data from "../../DUMMY_DATA";
import ItemList from "./ItemList";
const HomePage = () => {
const availableItems = data.map((products) => (
<ItemList
key={products.id}
images={products.image}
name={products.name}
price={products.price}
category={products.category}
size={products.size}
/>
));
return (
<Fragment>
<div>{availableItems}</div>
</Fragment>
);
};
export default HomePage;
My child component. Here, console logging shows the correct path, but the <img> tag is not rendering it.
import { Fragment } from "react";
const ItemList = (props) => {
const { id, images, name, price, category, size, inStock } = props;
return (
<Fragment>
<div className="container text-center">
<div className="row row-cols-4" key={id}>
<div className="col">
<img src={images} />
</div>
<div className="col">{name}</div>
<div className="col">{size}</div>
<div className="col">{price}</div>
</div>
</div>
</Fragment>
);
};
export default ItemList;
// while accessing the object values from data, I'm getting undefined in map
// ../data/section1
const data = [{
id: 1,
image: './images/homepage/xbox-games.png',
text: 'Buy Xbox games and consoles',
}, {
id: 2,
image: './images/homepage/shop_surface_devices.webp',
text: 'Shop surface devices',
}, {
id: 3,
image: './images/homepage/choose_your_ms_365.png',
text: 'Choose your Microsoft 365',
}, {
id: 4,
image: './images/homepage/shop_windows_10.png',
text: 'Shop Windows 10',
}]
export default data;
// the actual component
import data from "../data/section1";
const Section1 = () => {
return (
<>
<div class="mx-20">
{data.map((vals) => {
<div class="">
<img src={vals.image}/>
<p>{vals.text}</p>
</div>
})}
</div>
</>
)
}
export default Section1;
return JSX from the map
import data from "../data/section1";
const Section1 = () => {
return (
<>
<div class="mx-20">
{data.map((vals) => {
return (
<div class="">
<img src={vals.image}/>
<p>{vals.text}</p>
</div>
)
})}
</div>
</>
)
}
export default Section1;
I had the same problem, then tried the first bracket instead of the second, and it resolved the problem
import data from "../data/section1";
const Section1 = () => {
return (
<>
<div class="mx-20">
{data.map((vals) => (
<div class="">
<img src={vals.image}/>
<p>{vals.text}</p>
</div>
))}
</div>
</>
)
}
export default Section1;
I am working on a personal project where NFL Data is displayed by team. I am just learning React and would like to know how to use props and map image urls from an array to display multiple NFL logo cards. I have made a similar website using strictly css, html, and javascript but need to do it in react, anyways, this is what I have:
Home.js
import React from "react"
import { Link} from "react-router-dom"
import Box from '#material-ui/core/Box';
const teams = [
{
id: 1,
teamName: "Kansas City Cheifs",
urlImage: "public/chiefs_logo.jpg"
},
{
id: 2,
teamName: "Cincinatti Bengals",
urlImage: "public/Bengals.jpg"
},
{
id: 3,
teamName: "Denver Broncos",
urlImage: "public/Denver-Broncos-symbol.jpeg"
},
{
id: 4,
teamName: "Carolina Panthers",
urlImage: "public/panthers.png"
}
];
export default function Home(props) {
return (
<div className="Team-Box">
const teamCards = teams.map(team => )
<Box className="Box" key={teams.id} background-image={props.urlImage}/>
<Box className="Box" background-image={props.urlImage}/>
<Link to="/Home"></Link>
</div>
)
}
What it looks like so far
[What I want it to look like][2]
[2]: https://i.stack.imgur.com/KK0tw.jpg, except for all 32 NFL teams
Inside of your return you want something like this.
return (
<div>
{teams.map((team) => (
<div key={team.id} className='Team-Box'>
<Box
className='Box'
style={{ backgroundImage: `url(${team.imageUrl})` }}
/>
</div>
))}
<Link to='/Home'></Link>
</div>
);
Here is an idea of what this would look like if you wanted to pass some data as props to a Card component responsible for displaying the information on each team.
import { useState } from 'react';
const initialTeams = [
{
id: 1,
teamName: 'Kansas City Chiefs',
urlImage: 'public/chiefs_logo.jpg',
},
{
id: 2,
teamName: 'Cincinatti Bengals',
urlImage: 'public/Bengals.jpg',
},
{
id: 3,
teamName: 'Denver Broncos',
urlImage: 'public/Denver-Broncos-symbol.jpeg',
},
{
id: 4,
teamName: 'Carolina Panthers',
urlImage: 'public/panthers.png',
},
];
const Card = ({ imageUrl, teamName }) => (
<div className='team-card' style={{ backgroundImage: `url(${imageUrl})` }}>
{teamName}
</div>
);
const Home = () => {
const [teams, setTeams] = useState(initialTeams);
return (
<div>
{teams.map(({ id, imageUrl, teamName }) => (
<Card key={id} imageUrl={imageUrl} teamName={teamName} />
))}
</div>
);
};
export default Home;
I want to pass down an array of Objects to a child component. Each child component should return the value of the respective index of dummyData.
Parent Component
export default function MainContent() {
const dummyData = [
{
id: "1",
cardIMG: "test.png",
cardTitle: "Title",
cardText: "Text"
},
{
id: "2",
cardIMG: "test1.png",
cardTitle: "Title",
cardText: "Text"
}
];
return (
<div className="MainContainer">
<Card props={dummyData} />
<Card props={dummyData} />
</div>
);
}
Child Component
export default function Card(props) {
return (
<div className="CardContainer">
<div className="CardIMG">
<img src={this.props.CardIMG} alt="" />
</div>
<div className="TextContent">
<h2>{this.props.CardTitle}</h2>
<p className="TextBlock">{this.props.CardText}</p>
<button className="ReadMore">Read more</button>
</div>
</div>
);
}
Since you are trying to iterate through an array, you have to loop through the items. You can use for, map or each, totally upto you.
Refer loops: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
You can basically do this in your parent component:
export default function MainContent() {
const dummyData = [
{
id: "1",
cardIMG: "test.png",
cardTitle: "Title",
cardText: "Text"
},
{
id: "2",
cardIMG: "test1.png",
cardTitle: "Title",
cardText: "Text"
}
];
return (
<div className="MainContainer">
{dummyData.map((data) => {
<Card key={data.id} cardInfo={data} />
})
</div>
);
}
And in your child component(which is a functional component, so you can't use this in there), you can do
export default function Card(props) {
return (
<div className="CardContainer">
<div className="CardIMG">
<img src={props.cardInfo.cardIMG} alt="" />
</div>
<div className="TextContent">
<h2>{props.cardInfo.CardTitle}</h2>
<p className="TextBlock">{props.cardInfo.CardText}</p>
<button className="ReadMore">Read more</button>
</div>
</div>
);
}
I am facing a bit of a problem. I have two components. One parent component that is called goals and under different instances of goal. I am updating state of the parent component by passing a function to its children. The state of the parent is updated however only one of the child who made the change apply the change they should be all the same
Goals
import UserGoal from "./UserGoal";
import { Button, Container, Form, InputGroup } from "react-bootstrap";
import React, { useState, useEffect } from "react";
import "./UserGoal.css";
import { Link } from "react-router-dom";
const UserGoals = () => {
var test = [
{
id: 1,
name: "Marriage",
icon: "Marriage.png",
isSelected:false,
style: "goal-category"
},
{
id: 2,
name: "Car",
icon: "Car.png",
isSelected:false,
style: "goal-category"
},
{
id: 3,
name: "Home",
icon: "Home.png",
isSelected:false,
style: "goal-category"
},
{
id: 4,
name: "Education",
icon: "Education.png",
isSelected:false,
style: "goal-category"
},
{
id: 5,
name: "Travel",
icon: "Travel.png",
isSelected:false,
style: "goal-category"
},
{
id: 6,
name: "Retirement",
icon: "Retirement.png",
isSelected:false,
style: "goal-category"
},
{
id: 7,
name: "Other",
icon: "Other.png",
isSelected:false,
style: "goal-category"
},
]
const [goals, setGoals] = useState(test)
const changeSelection = (id) => {
const newarr = goals.map((GoalType)=> {
if(GoalType.id===id){
GoalType.isSelected=true
GoalType.style= "goal-category2"
}
else {
GoalType.isSelected=false
GoalType.style= "goal-category"
}
return GoalType
})
forceUpdate(newarr)
console.log(goals);
}
const forceUpdate = React.useCallback((arr) => {
setGoals(arr);
}, []);
return (
<Container>
<h1>Your saving goal</h1>
<div className="goal-categories">
{goals.map((GoalType) => (
<UserGoal
id={GoalType.id}
name={GoalType.name}
icon={GoalType.icon}
isSelected={()=>GoalType.isSelected}
style={()=>GoalType.style}
key={GoalType.id}
onClick={changeSelection}
></UserGoal>
))}
</div>
<div className="reg-wrapper">
<div className="reg-inner">
<Form className="ctr-form">
<Form.Label>Amount</Form.Label>
<InputGroup className="mb-3">
<Form.Control
className="input"
type="number"
placeholder="0.00"
/>
<div className="input-group-text">SAR</div>
</InputGroup>
<Form.Label>Date</Form.Label>
<InputGroup className="mb-3">
<Form.Control className="input" type="date" />
</InputGroup>
<div className="btn">
<Link to="/expenses">
<Button id="btn btn-primary" className="dbtn">
Next
</Button>
</Link>
</div>
</Form>
</div>
</div>
</Container>
);
}
export default UserGoals
Goal
import React from "react";
import { useState } from "react";
import "./UserGoal.css";
import { useEffect } from "react";
export default function UserGoal({ id, name, icon, isSelected, style, onClick }) {
const [style_, setStyle_] = useState(style())
return (
<>
<div className="goal-category-container">
<div
onClick={()=>{
onClick(id);
setStyle_(style())
}}
className={style_}
>
<div className="icon-wrap">
<img src={"assets/" + icon} alt="Goal Icon" />
</div>
</div>
<div className="category-name">{name} </div>
</div>
</>
);
}
You call setStyle_ immediately after the callback, even though the effects of the callback are asynchronous. Ie, the style won't be updated yet because the patent is doing an asynchronous setState.
Instead send down style as a value, not a function. That way the child will react to updates. Also having style as state oh the child is unnecessary, since you can just rely on the prop.
Also, don't use mutation in your map function. Instead create new goal objects. And your React.useCallback is equivalent to using the setter directly, it can be removed.