-1

I want to load data from a json file i made. i saw some tutorial on the web but they all have js and html. my app has tsx format and im so new to the react. i found this link but cant figure it out: https://www.pluralsight.com/guides/load-and-render-json-data-into-react-components. the file is something like this:

[
    {
        "id": "1",
        "Title": "Title 1",
        "Body": "Lorem Ipsum Text 1"
    },

    {
        "id": "2",
        "Title": "Title 2",
        "Body": "Lorem Ipsum Text 2"
    },

    {
        "id": "3",
        "Title": "Title 3",
        "Body": "Lorem Ipsum Text 3"
    }
]

my blog tsx is like this:

import React from "react";

const _Blog = (props: any) => {
  return (
    <>
      <article className="blog-post-item">
        <h2>TITLE</h2>
        <p>BODY</p>
        <small>ID</small>
      </article>

      <article className="blog-post-item">
        <h2>TITLE</h2>
        <p>BODY</p>
        <small>ID</small>
      </article>
      
      <article className="blog-post-item">
        <h2>TITLE</h2>
        <p>BODY</p>
        <small>ID</small>
      </article>
      
    </>
  );
};

export const Blog = _Blog;

I read some tutorial on the web but cant find for tsx format this is my app.tsx:

import React from "react";

import { HashRouter, NavLink, Route } from "react-router-dom";

import { Home, About, Contact, Courses, Blog } from "./pages";

import { LayoutProvider } from "./layout";

interface AppProps {}

const App: React.FC<AppProps> = (props) => {
  return (
    <HashRouter>
      <LayoutProvider>
        <div className="content">
          <Route exact path="/" component={Home} />
          <Route path="/About" component={About} />
          <Route path="/Contact" component={Contact}/>
          <Route path="/Courses" component={Courses}/>
          <Route path="/Blog" component={Blog}/>
        </div>
      </LayoutProvider>
    </HashRouter>
  );
};

export default App;
amir
  • 21
  • 3
  • Does this answer your question? [loading json data from local file into React JS](https://stackoverflow.com/questions/31758081/loading-json-data-from-local-file-into-react-js) – Yasin Aug 20 '20 at 09:19

1 Answers1

1

if you're using transformers like webpack you can just

import menu from './json/menu.json';
console.log(menu);

webpack will assign the json data to variable menu for you

if not, then you need to fetch it yourself

fetch('./json/menu.json')
    .then(res => res.json())
    .then((menu) => {
        console.log(menu);
    })
arslan2012
  • 871
  • 6
  • 18