Reputation: 199
I am iterating a block of JSX code that is getting its data from a json file, and is being displayed to the DOM. I need to apply a style to the first iteration in my map function but the rest need to be blank.
The training variable holds data from my json file. I need to apply a style of "marginRight:'5%'" to the first iteration of this map method.
trainer.js
{ training.map((course, index) => {
return (
<Course name={course.name}
school={course.school}
location={course.location}
year={course.year}
class={classes}
key={index}
style={{marginRight: '5%'}} <- this works but applies the style to all courses, which is not what I want.
/>
)
})}
trainerTemplate.js - This is the template that gets rendered. Props gets passed here from trainer.js
function Course(props){
return (
<Fragment>
<Grid item style={props.style}>
I'm assuming I need to set up a ternary operator somewhere that checks for an index of 0, but I can't seem to get anything to work
Upvotes: 2
Views: 73
Reputation: 4182
If you conditionally want to set margin for first item alone, you can try this: This one passes style attr for firstone, and refrains from over-writing previously set margin if in case index doesn't belong to the first element.
{training.map((course, index) => {
return (
<Course
name={course.name}
school={course.school}
location={course.location}
year={course.year}
class={classes}
key={index}
style={index === 0 ? { marginRight: "5%" } : {}}
/>
);
})}
Upvotes: 2
Reputation: 4322
Try this, I think it's a little clearer than doing it inline:
{ training.map((course, index) => {
const style = index === 0 ? { marginRight: '5%' } : null; // then use this as the style later
return (
<Course
name={course.name}
school={course.school}
location={course.location}
year={course.year}
className={classes} // also change this to className, not class
key={index} // if you can, avoid using the index as the key
style={style}
/>
)
})}
Upvotes: 3
Reputation: 478
it is as same as @Kai Qing ansewr
{ training.map((course, index) => {
return (
<Course name={course.name}
school={course.school}
location={course.location}
year={course.year}
class={classes}
key={index}
style={{marginRight: index === 0 ? '5%' : ''
}}
/>
)
})}
Upvotes: 3