I am practicing how to use the map function.
I have created a json file and want to display each data using map function.
The data is transferred very well. But the problem is the way the image is displayed.
The images are all in one file, and the way to display the image is to use background-position
to display part of the image.
To do this, I put the 'background-position' value of 'target' into a json file.
question
But I don't know how to pass this numerical value. Tried writing code but it doesn't work.
I think the way of passing the value to the style component is wrong. How do I display different images?
The problematic place is the place with id list__img
.
If you look at codespan it will be easier for you to understand the code.
Code
import { useState } from "react"; import styled from "styled-components"; import dummy from "./database/DB.json"; export default function App() { const [data, setData] = useState(dummy.products); return ( <Wrap> <div className="characterList"> <div className="word"> <h2 className="word__font">Like Pick!</h2> </div> <div className="list"> <ul className="list__ul"> {data.map((item) => { return ( <div className="list__box"> <Card key={item.id} item={item} /> </div> ); })} </ul> </div> </div> </Wrap> ); } // I think I need to deliver the value here function Card({ item }) { return ( <div className="list__wrap"> <div className="list__img" /> {item.nameKr} </div> ); } const Wrap = styled.div` border: 1px solid black; position: relative; top: calc(50vh - 100px); width: 1200px; display: inline-flex; .characterList { border: 1px solid red; } .word { margin: 0 auto; width: 1200px; } .word__font { font-family: "SFCompactDisplay-Bold", sans-serif; font-weight: bold; font-size: 38px; margin-bottom: 25px; text-align: center; } .list { border: 3px solid grey; margin: 0 auto; width: 1200px; padding-bottom: 20px; } .list__ul { display: inline-flex; list-style: none; } .list__box { margin: 0 9px; text-align: center; font-size: 17px; } .list__wrap { color: #333; font-size: 13px; display: inline-block; text-align: center; } .list__img { background-image: url(https://www.kakaofriendsgolf.com/img/v3_img_sprites_friends@3x.png); background-repeat: no-repeat; width: 70px; height: 70px; background-size: 100%; margin-bottom: 5px; /* 这部分是问题所在 */ background-position: 0 {item.position}%; } `;
database
{ "products": [ { "id": "1", "name": "choosik", "nameKr": "춘식이", "position": 17.647059 }, { "id": "2", "name": "ryan", "nameKr": "라이언", "position": 88.235295 }, { "id": "3", "name": "apeach", "nameKr": "어피치", "position": 5.882353 } ] }
Code span
https://codesandbox.io/s/characterselectmap-t2mqef?file=/src/App.js:0-1990
You can pass parameters into styled components.
But your way doesn't work.
Split 'list__img' into a new styled component, then you can access these props.
Or you can style it inline