How to set different X values for every map element. [left='X' px]. In short how to set a new className [class in Vanilla Js] property to the map generated elements.
const sports = [ //objects
{
id: 1,
name: 'A',
},
{
id: 2,
name: 'B',
},
{
id: 3,
name: 'C'
}
]
const sportList = sports.map(sport => (//mapped results in array sportList
<div className = "show-test" >
<div className = "show" > {sport.name} < /div>
<div className = "channel-time" >
{
dStart.getHours() ':'
dStart.getMinutes() ' - '
dEnd.getHours() ':'
dEnd.getMinutes()
}
</div>
</div>
)
)
return (
<>
<div className = "show-div" >
<div className = "show-item-name" >
<div className = "show-test2" > {sportList} </div>
</div>
</div>
</>
)
CodePudding user response:
if you are talking about adding diffrent classes to mapped result:
const sports = [{ //object
id: 1,
name: 'A',
class:"class1"
},
{
id: 2,
name: 'B',
class:"class2"
},
{
id: 3,
name: 'C'
class:"class3"
}
]
const sportList = sports.map(sport => ( //mapped results in a new array sportsList
<div className = {sport.class} >
<div className = "show" > {sport.name} < /div> <div className = "channel-time" >
{dStart.getHours() ':' dStart.getMinutes() ' - ' dEnd.getHours() ':' dEnd.getMinutes()}
</div>
</div>
))
return ( <
>
<div className = "show-div" >
<div className = "show-item-name" >
<div className = "show-test2" > {sportList}
</div>
</div>
</div>
</>
)
CodePudding user response:
I'm not sure exactly where you are trying to add the className in this example. But if it is inside this map then you can find the index by adding index
into the .map
args, e.g.
const sportList = sports.map((sport, index) => ( //mapped results in a new array sportsList
<div className = `show-test your-class-${index}` >
<div className = "show" > {sport.name} < /div> <div className = "channel-time" >
{dStart.getHours() ':' dStart.getMinutes() ' - ' dEnd.getHours() ':' dEnd.getMinutes()}
</div>
</div>
))
CodePudding user response:
Within the map callback function, you can generate a unique className
from the current index in the array.
eg
className={`show-test show-test-${i}`}
const sports = [
{
id: 1,
name: "A"
},
{
id: 2,
name: "B"
},
{
id: 3,
name: "C"
}
];
const App = () => {
return (
<>
{sports.map((sport, i) => (
<div className={`show-test show-test-${i}`}>
<div className="show"> {sport.name} </div>
</div>
))}
</>
);
};
export default App;
You can do the same thing with any attribute, such as style
.
const sports = [
{
id: 1,
name: "A"
},
{
id: 2,
name: "B"
},
{
id: 3,
name: "C"
}
];
const App = () => {
return (
<>
{sports.map((sport, i) => (
<div
className="show-test"
style={{
marginLeft: i * 20 "px"
}}
>
<div className="show"> {sport.name} </div>
</div>
))}
</>
);
};
export default App;