Paul Nylund
Paul Nylund

Reputation: 371

React.js and JSON: Dynamic Styles?

I'm building a site with React.js, and I'm having trouble using a hex value stored in a json file as the background color of an object. Somehow, the data isn't making its way over to the javascript file (this is my first time using JSON), as it is having no effect on the rendered style or content. This goes for the color, text, etc. Assistance would be much appreciated. Thanks in advance!

The Javascript (ListItem.js):

import data from './data.json';

class ListItem extends Component {

  render() {

    var listItems = data.listItems;
    var color = listItems.color;
    var text = listItems.text;

    var listItemStyle = {

      width: '100px',
      minHeight: '100px',
      backgroundColor: color,
      color: '#FFFFFF'
    }

    return (

      <div style={listItemStyle}>
        <h1>{text}</h1>
      </listItemStyle>
    );
  }
}

export default listItem

The JSON (data.json):

{ "listItems" : [

  { "color" : "#000000",
    "text" : "hello world"
}]}

Upvotes: 1

Views: 6577

Answers (2)

Farbod Aprin
Farbod Aprin

Reputation: 1186

You had some syntax error. and as CodinCat said you need an array for reading the Json file. here is the complete code and JSON file.

JS Code:

import data from './testJson2.json';
import React, {Component} from 'react';

class ListItem extends Component {
        render() {
            let listItems = data.listItems;
            let listItemStyle = {
                width: '300px',
                minHeight: '300px',
                backgroundColor: listItems[0].color,
                color: '#ff571a'
            };
            return (
             <div style={listItemStyle}>
                {listItems[0].text}
            </div>
            );
        }
    }

    export default ListItem

Json file:

{
  "listItems": [
    {
      "color": "#FFF51E",
      "text": "Rendered Json"
    }
  ]
}

Output => render style/css from JSON file in React JS:

render style/css from JSON file in React JS

Upvotes: 0

CodinCat
CodinCat

Reputation: 15914

You listItems in data.json is an array.

{
  "listItems": [ <--- array
    {
      "color": "#000000",
      "text": "hello world"
    }
  ]
}

So when you access listItems.color you get undefined. Use listItems[0].color or update your data.json to

{
  "listItems" {
    "color": "#000000",
    "text:": "hello world"
  }
}

Upvotes: 1

Related Questions