Working With JSON Data In ReactJS
A basic introduction to JSON and how you can use it in ReactJS
This article is sponsored by Recro.
Recro is a developer centric platform providing them with an opportunity to work with fast growing startups. Be a part of their exclusive discord community for Java & JavaScript developers to learn, build meaningful connections & grow. Check them out and skyrocket your career 🚀.
Recently, I contributed to ReactPlay - an open-source platform that helps you learn ReactJS. As a part of this contribution, I created a play(project) where users can copy the TailwindCSS, CSS and colour codes used in a gradient. When working on this project, I used JSON to store all the information about the gradients and used it in the project.
Although I didn't face any problems working with JSON, I found that a lot of developers, either don't know about JSON that much or don't take it seriously. So in this article, I figured I'd talk about JSON and how you can use it in your React projects. So without any further delay, let's dive in.
What is JSON?
Before we start using JSON data in React, let's try to have a basic understanding of JSON. So, what is JSON?
JavaScript Object Notation or JSON in short is a standard text-based format for representing structured data based on JavaScript object syntax. Although it inherits from JavaScript, it is not restricted to being used only with JavaScript. All modern programming languages support the data structures of JSON, thus making it completely language-independent.
JSON is basically used in storing data, which has grown to be a key part of most development workflows. If you a building an application that uses an external API, that API is probably in the form of JSON objects or even if you are building your own API, you are most likely to use JSON objects to store data.
Why JSON?
The rise in JSON's popularity is caused by a need for applications to store, consume, and transfer data efficiently. And although there are other formats out there you could use, like XML, YAML and CSV, JSON has proven to be more efficient and easy to use. And before the introduction of JSON, XML was widely used for data storage, and transmission. And I think that the primary reason why JSON surpassed these alternatives was because of its flexibility, efficiency and it's incredibly simple syntax compared to something like XML.
Some features of JSON:
- Simplicity
- Openness
- Self-Describing
- Internationalization
- Extensibility
- Interoperability
The basic JSON structure, syntax and usage
As I said earlier, JSON's simple syntax is one of the main reasons why developers switch to JSON. It's easy to write, read and translate between many different programming languages. This means that if a JavaScript developer created an API with JSON, a Python programmer is also able to use this API because of the consistent structure of JSON.
Here's the structure of a JSON object:
- Use curly braces
{}
to hold objects. - Use square brackets
[]
to hold arrays. - The data is stored as key-value pairs.
- Each data element is enclosed with quotes if it is a character or without quotes if it is a numeric/boolean value.
- Commas are used to separate each piece of data.
Here are the data types you can use in JSON:
- string – Literal text that’s enclosed in quotes.
- number – Positive or negative integers or floating point numbers.
- object – A key, value pair enclosed in curly braces
- array – A collection of one or more JSON objects.
- boolean – A value of either true or false with no quotes.
- null – Indicates the absence of data for a key-value pair, represented as “null” with no quotes.
Here's a simple example of a JSON object:
{
"name": "Ammaar Aslam",
"age": 17,
"mainStack": ["React", "JavaScript", "Next.js", "TailwindCSS", "MySQL", "Prisma"],
"developer": true,
"knowsJava": null
}
Using JSON in React
Now that we have a basic understanding of JSON, let's use data from JSON and display it in our React application.
- The first step to do this is obviously to create a React app first with
npx create-react-app json-example
, then clean up unnecessary code that comes with the boilerplate. Then create a new file called
data.json
. in this file you can create your own data and use it accordingly or here's what I'm using:[ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, { "userId": 1, "id": 3, "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut", "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut" }, ]
I got this data from jsonplaceholder at jsonplaceholder.typicode.com/posts
Now that we have our data, let's import it to our application (you have to import it to the file that you are going to use the data in. For example in
App.js
):import data from 'data.json'
- To display the data in our application we can simply access the properties as you would with a regular JavaScript object:
But since we are using an array of objects, we can use the<h1>{data.title}</h1>
.map()
function to iterate through the array and display the data like the following:{data.map((post) => { <div key={post.id}> <h1>{post.title}</h1> <p>{post.body}</p> </div> })}
- The next step is styling the data which is totally up to you to decide.
There you have it, you have successfully used data from JSON and displayed in your React app.
Here's the full code I used for the React part:
import React from 'react'
import './styles.css'
import data from './data.json'
const Posts = () => {
return (
<>
{data.map((post) => {
<div key={post.id}>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
})}
</>
)
}
export default Posts
More Resources
Here are some resources if you want to dive deeper into learning JSON:
- developer.mozilla.org/en-US/docs/Learn/Java..
- freecodecamp.org/news/what-is-json-a-json-f..
- javatpoint.com/json-tutorial
Conclusion
Getting familiar working with JSON is an important part of a developer, especially in web development. Go try it out, build a simple project that uses data from JSON and beautifully displays it to the user. Another addition to this would be to make your own set of data and make it accessible to others in the form of an API. If you are interested in this, I wrote an article where I describe 5 projects that you can build to improve your web development skills.
...And thanks for reading! If you learned something new today or find this article to be useful, consider liking and sharing it with others. If I missed anything let me know in the comments down below.
And as always, if you have any questions or feedback let me know in the comments down below and follow me on Twitter for more updates on my journey, tips and tricks about programming.