1

There is json in the project which contains the data that I need to display in the component. How to correctly access the json file in react and output data from json?

data.json

{
  "dictionary": [
    {
      "index": "1",
      "engwords": "Hello",
      "ruswords": "Привет"
    },
    {
      "index": "2",
      "engwords": "How are you?",
      "ruswords": "Как твои дела?"
    },
    {
      "index": "3",
      "engwords": "How old are you?",
      "ruswords": "Сколько тебе лет?"
    }
  ]
}

component.js

import React, {Component} from "react";
import "./style.scss";
const dictionary = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionary.map(elem => (
                    <p>{elem}</p>))}
            </div>
        );
    }
};
0

2 Answers 2

3

This renders everything in your JSON

import React, {Component} from "react";
import "./style.scss";
const dictionaryFile = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionaryFile.dictionary.map(elem => (
                    <div>
                       <p>{elem.index}</p>
                       <p>{elem.engwords}</p>
                       <p>{elem.ruswords}</p>
                    </div>
                  ))
                }
            </div>
        );
    }
};
Sign up to request clarification or add additional context in comments.

Comments

0

All Keys and values will be displays

import React, {Component} from "react";

import "./style.scss";
const dictionaryFile = require ('./../../dictionary/dictionary.json');

export default class Test extends Component {
    render() {
        return (
            <div className="test">
                {dictionaryFile.dictionary.map(elem => (
                    <div>
                    {Object.keys(elem).forEach(function(key) {
                      <p>{key}: { elem[key]}</p>
                      });}
                    </div>
                  ))
                }
            </div>
        );
    }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.