I want to prepare my component to receive an JSON object from the backend. So in my main component, I've got a state :
constructor(props) {
super(props);
this.state = {
contributions : {
[
{
name: 'Test',
value: '1',
},
{
name: 'Test2',
value: '12',
},
]
}
render() {
const { contributions } = this.state;
return (
<MyComponent contributions={contributions} />
);
}
So now, I want to know the best solution to render my object in MyComponent so I can have for output :
<div>
<span class="name">Test</span>
<span class="value">1</span>
</div>
<div>
<span class="name">Test2</span>
<span class="value">12</span>
</div>
JSON objects are key-value pairs. So if you're saving the JSON to your state, it can look something like
this.state = {
contributions : {
"nameValuePairs":[
{
"name": 'Test',
"value": '1',
},
{
"name": 'Test2',
"value": '12',
},
]
}
Now to map through the objects you can do something like
{this.state.contributions.nameValuePairs.map((item)=>(<TestChild item={item}/>))
Bascially your parent would look something like
import React, { Component } from 'react';
import TestChild from './TestChild'
class Test extends Component {
constructor(props) {
super(props);
this.state = {
contributions : {
"nameValuePairs":[
{
"name": 'Test',
"value": '1',
},
{
"name": 'Test2',
"value": '12',
},
]
}
}
}
render() {
return (
<div>
{this.state.contributions.nameValuePairs.map((item)=>(<TestChild item={item}/>))}
</div>
);
}
}
export default Test;
and your child component can have inside it, something like
render () {
return (
<div>{this.props.item.name}</div>
<div>{this.props.item.value}</div>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With