Home > Web Front-end > JS Tutorial > How to reference json in react

How to reference json in react

coldplay.xixi
Release: 2020-11-26 16:20:25
Original
4741 people have browsed it

Methods to reference json in react: 1. Import directly and use [create-react-app] to build the project; 2. Change the json file to a js file and assign the data in the original json to variables data.

How to reference json in react

  • This method is suitable for all brands of computers

react Methods of quoting json in:

The first way: directly import

You need to use the json-loader module, if you are Use create-react-app to build the project, then the module is already included.

You only need to use import to introduce the json file like a component, import data from '. ./lessonlist/courselist.json';

data is the name I chose myself, similar to the component name. There is no need to export default data to export, but writing this in the json file will also report an error

How to reference json in react

Second: Change the json file into a js file

Change the json file into a js file, and then assign the data in the original json to the variable data,

Just use import to introduce it, import data from '../lessonlist/courselist.js';

How to reference json in react

These two methods to access data are as follows

<span className="lesson-link-line1">{data[0].name}</span>
<span className="lesson-link-line1">{data[0].url}</span>
<span className="lesson-link-line1">{data[1].name}</span>
<span className="lesson-link-line1">{data[1].url}</span>
<span className="lesson-link-line1">{data[2].name}</span>
<span className="lesson-link-line1">{data[2].url}</span>
Copy after login

The main difference between these two methods

  • json files do not need to be exported by default, and this syntax is not supported, and an error will be reported.

  • js file needs to assign data to a variable. In the export default export,

  • The attributes and values ​​in the json file must be double Quotes, otherwise an error will be reported. js file attributes do not need to be double quotes

Related free learning recommendations: javascript (video)

The above is the detailed content of How to reference json in react. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template