Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React : Best way to put dummy content in a component

Tags:

reactjs

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>
like image 458
Kaherdin Avatar asked Nov 22 '25 00:11

Kaherdin


1 Answers

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>
 )
}
like image 93
illiteratewriter Avatar answered Nov 24 '25 16:11

illiteratewriter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!