Passing JSON values as props
Passing JSON values as props in React involves sending structured data objects from parent components to child components. This approach enables efficient data transfer and facilitates dynamic rendering, and helps developers to leverage JSON data for dynamic content display, state management, and application functionality within React components.
Example: In this example, the Account component receives the user prop containing the JSON data, which it can then use to display the user’s name and ID.
/*Account.css*/
.centered {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
height: 100vh;
}
.green-text {
color: green;
}
// App.js
import React, { Component } from "react";
import Account from "./Account";
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: {
id: 12,
firstName: "Bishal",
lastName: "Paul",
},
};
}
render() {
return (
<div>
<Account user={this.state.user} />
</div>
);
}
}
export default App;
// Account.jsx
import React from 'react'
import './Account.css'
const Account = (props) => {
const { user } = props
return (
<div className="centered">
<h1 className="green-text">
w3wiki
</h1>
<span>
Name - {user.firstName} {user.lastName}
</span>
<br />
<span>ID - {user.id}</span>
</div>
)
}
export default Account
Output:
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"
}