Passing Array JSON
Passing arrays in JSON allows you to send multiple values in a single variable. JSON is a lightweight data-interchange format that is not user friendly for humans to read and write, and easy for machines to parse and generate.
Example: Implementation to show passing array JSON form one component to another.
// App.js
import React from 'react'
import ChildComponent from './ChildComponent.jsx'
const ParentComponent = () => {
const data = [
{ id: 1, name: 'Bishal' },
{ id: 2, name: 'Baishali' },
{ id: 3, name: 'Rahul' }
]
return (
<div style={{ textAlign: 'center', color: 'green' }}>
<h1>w3wiki</h1>
<p>Parent Component</p>
<ChildComponent data={data} />
</div>
)
}
export default ParentComponent
// ChildComponent.js
import React from 'react';
const ChildComponent = ({ data }) => {
const jsonData = JSON.stringify(data);
return (
<div>
<p>Child Component</p>
<pre>{jsonData}</pre>
</div>
);
};
export default ChildComponent;
Output:
Conclusion:
In React, passing JSON values as props is a common way to send data from a parent component to its child components. Props allow components to be dynamic and reusable, as they can receive different JSON data based on the parent’s state or other factors. JSON arrays can also be passed as props, allowing for the transmission of multiple values in a single variable. JSON’s simplicity and readability make it an ideal format for transmitting complex data structures between components in a React application.
How to Pass JSON Values into React Components ?
In React, you can pass JSON values into components using props. Props allow us to send data from a parent component to its child components. When rendering a component, you can pass the JSON values as props. These props can then be accessed within the component’s function or class, allowing you to display the desired data.
Table of Content
- Passing JSON values as props
- Passing Array JSON
Steps to Setup the Application:
Step 1: Create a reactJS application by using this command
npx create-react-app myapp
Step 2: Navigate to the project directory
cd myapp
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}