When you are iterating over an object you'll want to use a function that gets data from your object in an array. Traditionally that is Object.keys()
, but newer versions of Javascript introduced Object.values()
and Object.entries()
which can be very helpful depending on the situation. You can access a value from its key like myObject[myKey]
so Object.keys()
can work in every situation.
The current structure of your JSON file is not ideal because you have totally separate objects for titles
and buttons
so you can't ensure that you have the same amount of title texts as button texts. I'll address this in a moment, but first here is one way that you can use the current structure.
const MySlider = () => {
const currentlang = ... // get the EN or FR object based on your current language
// an array of all the title texts
const titles = Object.values(currentlang.page1.section1.titles);
// an array of all the button texts
const buttons = Object.values(currentlang.page1.section1.buttons);
return (
<Slider>
{titles.map((title, i) => ( // map through the titles
<Slide
title={title}
buttonText={buttons[i]} // get the button text with the same index -- how do we know this is valid?
key={i} // i as a key is not great
/>
))}
</Slider>
);
};
With some dummy components so that you can render it:
const Slider: React.FC = ({ children }) => <div>{children}</div>;
interface SliderProps {
title: string;
buttonText: string;
}
const Slide: React.FC<SliderProps> = ({ title, buttonText }) => {
return (
<div>
<h2>{title}</h2>
<button>{buttonText}</button>
</div>
);
};
I would recommend grouping the labels by slide rather than by titles
and buttons
. This ensures that titles and buttons match up, allows easy access by the slide key if you want to customize the order, and gives us a unique key
property for our components.
export const EN = {
page1: {
section1: {
slides: {
sale: {
title: "title1_name",
button: "button1_name"
},
featured: {
title: "title2_name",
button: "button2_name"
},
promo: {
title: "title3_name",
button: "button3_name"
},
}
}
}
};
const MySlider = () => {
const currentlang = ... // get the EN or FR object based on your current language
// keyed object of slides
const slides = currentlang.page1.section1.slides;
return (
<Slider>
{Object.entries(slides).map(
// Object.entries gives us an array with elements key and value
([key, value]) => (
<Slide
title={value.title}
buttonText={value.button}
key={key}
/>
)
)}
</Slider>
);
};
Key-based approach to allow custom ordering:
const MySlider = () => {
const currentlang = ... // get the EN or FR object based on your current language
// keyed object of slides
const slides = currentlang.page1.section1.slides;
// helper function renders the slide for a given key
const renderSlide = (key: keyof typeof slides) => {
const {title, button} = slides[key];
return (
<Slide
title={title}
buttonText={button}
/>
)
}
return (
<Slider>
{renderSlide("promo")}
{renderSlide("sale")}
{renderSlide("featured")}
</Slider>
);
};