First of all you don't have a state in your app. You can't use this.state.something if there is not a state.
Secondly, do not use for loops in your render function like this. There are better ways to do this as suggested in the other answer. But if you really want to do this:
class App extends React.Component {
state = {
tags: {
foo: "somefoo",
bar: "somebar",
baz: "somebaz"
}
};
render() {
const { tags } = this.state;
const arr = [];
for (var key in tags) {
arr.push(<p className="h3 text-primary">{tags[key]}</p>);
}
return (
arr
);
}
}
But, render method is so crowded, let's make a little bit cleaning.
class App extends React.Component {
state = {
tags: {
foo: "somefoo",
bar: "somebar",
baz: "somebaz"
}
};
getTags = () => {
const { tags } = this.state;
const arr = [];
for (var key in tags) {
arr.push(<p className="h3 text-primary">{tags[key]}</p>);
}
return arr;
}
render() {
return (
this.getTags()
);
}
}
But there are better ways to iterate over stuff like .map or Object(keys) then .map for your example as suggested.
class App extends React.Component {
state = {
tags: {
foo: "somefoo",
bar: "somebar",
baz: "somebaz"
}
};
render() {
const { tags } = this.state;
return (
Object.keys(tags)
.map(key => <p key={key}>{tags[key]}</p>)
);
}
}
But again, you can use a separate function to get a cleaner structure for your render method.
class App extends React.Component {
state = {
tags: {
foo: "somefoo",
bar: "somebar",
baz: "somebaz"
}
};
getTags = () => {
const { tags } = this.state;
return Object.keys(tags)
.map( key => <p key={key}>{tags[key]}</p>)
}
render() {
return (
this.getTags()
);
}
}
Nice and clean! Don't forget if you need other JSX in here you have to use {} to use javascript expressions. For example what if you want a wrapper div top of your p's?
class App extends React.Component {
state = {
tags: {
foo: "somefoo",
bar: "somebar",
baz: "somebaz"
}
};
getTags = () => {
const { tags } = this.state;
return Object.keys(tags)
.map( key => <p key={key}>{tags[key]}</p>)
}
render() {
return (
<div>
{ this.getTags() }
</div>
);
}
}
let