I am having issues rendering elements dynamically in my React project.
This is my data file xxx.js
export const valuesText = [
{
"GB": {
0: "Responsibility",
1: "Hospitality",
2: "Attention to detail",
3: "Adaptability",
4: "Efficiency",
5: "Passion for Quality"
},
"PT": {
0: "Responsabilidade",
1: "Hospitalidade",
2: "Detalhe e pormenor",
3: "Adaptabilidade",
4: "Eficiência",
5: "Paixão pela Qualidade"
}
}
]
This is my component and the logic to render all the 5 topics depending in the language selected by the user (GB or PT)
Logic to render elements based on data
const textSectionValues = valuesText.map((data) => {
const values = data[props.language]
Object.values(values).map((item, index) => {
return <div className="hero_section_values_container">
<h3>{item[index]}</h3>
</div>
}
)})
Component adapted so the amount of info is not too noisy for you guys
const AboutUs = (props) => {
return(
<section className="about_us_section">
{textSectionValues}
</section>
)
}
Through Chrome Developer tools I can see the array created from Object.values being iterated and having the correct values. Unfortunately I haven't managed to render the content to the DOM.
What am I doing wrong?
Thank you!
CodePudding user response:
first, your first loop does not return anything.
second, you need print item
, because it is the real text.
const textSectionValues = valuesText.map((data) => {
const values = data[props.language];
return Object.values(values).map((item) => {
return (
<div key={item} className="hero_section_values_container">
<h3>{item}</h3>
</div>
);
});
});
working example: https://codesandbox.io/s/nameless-currying-n0es7
CodePudding user response:
Are you sure about your data structure? It's array contains only one object which contains the data, so the first map is redundant. Check this out
const valuesText = {
GB: {
0: "Responsibility",
1: "Hospitality",
2: "Attention to detail",
3: "Adaptability",
4: "Efficiency",
5: "Passion for Quality"
},
PT: {
0: "Responsabilidade",
1: "Hospitalidade",
2: "Detalhe e pormenor",
3: "Adaptabilidade",
4: "Eficiência",
5: "Paixão pela Qualidade"
}
};
export default function App(props) {
return (
<div className="App">
{Object.values(valuesText[props.language]).map((value, index) => (
<h1 key={index}>{value}</h1>
))}
</div>
);
}