Displaying JSON object in React( JSX ) is giving undefined - json

In my project I am receiving array from backend in that JSON object is ->
list=[{
deleted: false,
details:{
groupNumber: "123ddd",
insuranceName: "Blue Sheild insurance",
memberId: "12345",
payerId: "21212",
relationToSubscriber: null,
ssn: true,
subscriberDoB: "1991-01-01",
subscriberFirstName: "Payor A",
subscriberLastName: "Added",
subscriberMiddleName: "middle",
},
editStatus: "PENDING",
imageInfo: null,
tier: "PRIMARY",
},]
Passing data from parent component
<div className="insurance-sub-heading">Card detials</div>
{insuranceList.map((m, index) => (
<InsuranceList
key={index}
value={m}
index={index}
text={getInsuranceStatusText(m.editStatus)}
/>
))}
</div>
to child component
const{value}=props
return(
<div className="insurance-body">
<div className="insurance-icon-name">
<div className="drop-down-icon" onClick={() => openDrawer(index)}>
<img src={show.visible ? downArrow : rightArrow} />
</div>
<div className="name-bold">{value.details.insuranceName}</div>
</div>
<div className="insurance-icon-name">
<div className="insurance-status">{text}</div>
<div className="insurance-status-icon">
{getInsuranceStatus(value.editStatus)}
</div>
</div>
</div>
{show.visible && (
<div className="dropDown-container">
{!value.details.ssn && (
<React.Fragment>
<div className="text-container">
<div className="text-heading">Member / Subscriber ID</div>
<div className="text">{value.details.memberId}</div>
</div>
{/* {value.details.groupNumber.trim() !== '' && ( */}
<div className="text-container">
<div className="text-heading">Group number</div>
<div className="text">{value.detials.groupNumber}</div>
</div>
{/* )} */}
</React.Fragment>
)}
<div className="text-container">
<div className="text-heading">Subscriber name</div>
<div className="text">John (optional middle) Dee</div>
</div>
<div className="text-container">
<div className="text-heading">Subscriber date of birth</div>
<div className="text">04/12/2000</div>
</div>
<div className="text-container">
<div className="text-heading">Relationship to the patient</div>
<div className="text">Mother</div>
</div>
</div>
)}
)
Problem which I am facing is when Child component loads it gives error that value.detials.groupNumber is undefined, Although object is present inside the json object. By clicking button I can console the value.detials.groupNumber it prints the data but it is not displaying it on HTML side it shows Empty

Chances there's a list item without a groupNumber
Consider using conditional rendering like this
{value.detials.groupNumber &&
<div className="text">{value.detials.groupNumber}</div>
}
Note:
You have a typo on, it should be details, and not detials

Related

How can I get the ID of div inside a div wrapper. Jquery

I have a div that looks like this:
<div id="data" class="grid grid-cols-2">
</div>
and I have a function that can append in data div:
function loadStaticBar(data) {
let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
$('#data').append(`
<div class="flex flex-col" id="${pl_name}-wrapper">
<div class="static barchart" id="${pl_name}-plot">
</div>
</div>
`)
}
The content of loadStaticBar(data) is a key and value it's a details for charts:
{id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date', …}
Now, I'm trying to get all the IDs with the class static. I have tried:
$('#data').find('.static')
And I get S.fn.init [prevObject: S.fn.init(1)] inside of this are bunch of information. How can I get the IDs of the div that containing static class like this.
ids = [line-plot, bar-plot]
The answer to the updated question could be:
function loadStaticBar(data) {
let pl_name= `bar-${data.title.replace(/\s+/g, '-').toLowerCase()}`
$('#data').append(`
<div class="flex flex-col" id="${pl_name}-wrapper">
<div class="static barchart" id="${pl_name}-plot">
</div>
</div>
`)
}
const data={id: 453, title: 'Bar Chart Example', select: 'bar-form', xtitle: 'Values', ytitle: 'Date'};
$(function(){
loadStaticBar(data); // create the divs first !!!
const ids=$("#data .static").get().map(el=>el.id);
console.log(ids);
});
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<div id="data" class="grid grid-cols-2">
</div>
As you want to receive a "proper" array instead of a jQuery object it makes sense to .get() the selected DOM elements first and then .map() them using the standard Array-method.
Incidentally, you can solve the originally posted question also without jQuery:
document.addEventListener("DOMContentLoaded", function () {
const ids=[...document.querySelectorAll("#data .static")].map(el=>el.id);
console.log(ids);
});
<div id="data" class="grid grid-cols-2">
<div class="flex flex-col" id="line-wrapper">
<div class="static linechart" id="line-plot">
</div>
</div>
<div class="flex flex-col" id="bar-wrapper">
<div class="static barchart" id="bar-plot">
</div>
</div>
</div>

how can you render an HTML array?

I have an array with <p> and <div> items and I'm trying to render them as HTML, but whenever I try to render it, the values just appear as plain code and not the normal paragraphs. So I have an array with let's say that this information:
<p>The first paragraph of this pinned topic will be visible as a welcome message to all new visitors on your homepage. It’s important!</p>
<p><strong>Edit this</strong> into a brief description of your community:</p>
And when it gets rendered in the page, it gets rendered as this instead of the paragraph that should be rendered it gets rendered as plain code:
this is how it renders
This is the code I've used for render:
useEffect(() => {
axios.get(`/api/get-post?id=${pid}`)
.then(res => setPostData(res.data))
.catch(err => console.log(err.response))
}, [])
console.log(postData?.post_stream?.posts[0]?.cooked)
return (
<div>
<div className={styles.containerPadding}>
<div className={styles.mainContainer}>
<div className={styles.blackLine}>
</div>
<div className={styles.titleContainer}>
<div>
<h1>{postData.title}</h1>
</div>
<div>
<h1></h1>
</div>
</div>
<div className={styles.postInformationContainer}>
<div>
</div>
<div>
<p>{postData?.post_stream?.posts[0]?.cooked}</p>
</div>
</div>
</div>
</div>
</div>
You can use dangerouslySetInnerHTML for converting your string data to HTML, but for safety (avoiding XSS attack), you should sanitize your HTML string before using dangerouslySetInnerHTML by DOMPurify
import DOMPurify from 'dompurify'
const sanitizedHtml = DOMPurify.sanitize(postData?.post_stream?.posts[0]?.cooked)
And then call it like this
dangerouslySetInnerHTML={{__html: sanitizedHtml}}
useEffect(() => {
axios.get(`/api/get-post?id=${pid}`)
.then(res => setPostData(res.data))
.catch(err => console.log(err.response))
}, [])
const sanitizedHtml = DOMPurify.sanitize(postData?.post_stream?.posts[0]?.cooked)
return (
<div>
<div className={styles.containerPadding}>
<div className={styles.mainContainer}>
<div className={styles.blackLine}>
</div>
<div className={styles.titleContainer}>
<div>
<h1>{postData.title}</h1>
</div>
<div>
<h1></h1>
</div>
</div>
<div className={styles.postInformationContainer}>
<div>
</div>
<div>
<p dangerouslySetInnerHTML={{__html: sanitizedHtml}}></p>
</div>
</div>
</div>
</div>
</div>
One side note, without HTML string sanitization, your HTML data can be interfered by some script injections which would harm your website or your system.
You can use html-react-parser package
This is how your code will look like
import parse from 'html-react-parser'
useEffect(() => {
axios.get(`/api/get-post?id=${pid}`)
.then(res => setPostData(res.data))
.catch(err => console.log(err.response))
}, [])
return (
<div>
<div className={styles.containerPadding}>
<div className={styles.mainContainer}>
<div className={styles.blackLine}>
</div>
<div className={styles.titleContainer}>
<div>
<h1>{postData.title}</h1>
</div>
<div>
<h1></h1>
</div>
</div>
<div className={styles.postInformationContainer}>
<div>
</div>
<div>
<p>{parse(postData?.post_stream?.posts[0]?.cooked)}</p>
</div>
</div>
</div>
</div>
</div>
You can use 'dangerouslySetInnerHTML' like everyone else.
And I need to register the tags to use.
import DOMPurify from 'dompurify';
<div
dangerouslySetInnerHTML={{
__html: DOMPurify.sanitize(
view_inner ?? '<div>Unable to get data.</div>',
{
FORCE_BODY: true,
ADD_TAGS: ['style'],
ADD_ATTR: ['target'],
ALLOWED_TAGS: [
'span',
'div',
'link',
'table',
'thead',
'tr',
'th',
'tbody',
'td',
],
},
),
}}
/>

Error ',' expected.ts(1005) in html layout

This is the first time I am trying to build a real layout for my ReactJS project, but I ran into this error (Error ',' expected.ts(1005)) and can not get it off.
Here is the html of the layout I intend to build:
<div>
{selectedInput === null ? (
<div>
<div>
some html
</div>
<div>
{
array.slice(3, 100).map((doc, index) =>
<div>
some html
</div>
} <== here the error
</div>
</div>
) : (
<div>
some html
</div>
)
}
</div>
I encounter the error in the last brace
EDIT: I apologize to whoever replied, but I wanted to synthesize the code and I did a horrible job. Now I have put the correct version.
You missed the closing parenthesis) of map.
Try adding parenthesis.
Updated code:
<div>
{selectedInput === null ? (
<div>
<div>some html</div>
<div>
{array.slice(3, 100).map((doc, index) => (
<div>some html</div>
))}
</div>
</div>
) : (
<div>some html</div>
)}
</div>
You forgot to add closing braces, '}'.
This should work
<div>
{selectedInput === null ? (
<div>
<div>
some html
</div>
<div>
{
getOrder.slice(3, 100).map((doc, index) =>
<div>
some html
</div>
} <== here the error
</div>
</div>
}
</div>
Too many mistakes.
Feeling like you don't understand how it works.
This code should work, but you need to understand it thoroughly.
<div>
{selectedInput === null ? (
<div>
<div>some html</div>
<div>
{getOrder.slice(3, 100).map((item, i) => {
return <div key={i}>some html</div>;
})}
</div>
</div>
) : (
<div>Another content</div>
)}
</div>;

How can i create a dynamic page using parameter in react + Json

How can i create a dynamic page using parameter in react + Json
in my code below i was able to map the json data and i need to create a dynamic url that create the /download page with the json details of the artist when i click on "GET MP3" button.
example: When i click GET MP3 a new tab will open with a url like this https:// mysite.com/
then on the download page i can get all the details from the {data.id}.
Please any idea on how to go around it?
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import "../customcss/style.css";
import data from "../artist/toptrending5.json";
const newdata = data.map((item) => {
const searchDownloadData = `download?id=${item.id}&artist=${item.artist}&title=${item.title}&genre=${item.genre}&urldownload=${item.urldownload}`
return (
<>
<div id="playerbackground" key= {data.id} style={{marginTop: '10px'}}>
<div className="row" align="center">
<div className="col">
<img id="Playericon" src={ Playericon } />
</div>
<div className="col ">
<button id="music-play" type="button" className="btn btn-outline-warning"><b>Play</b></button>
</div>
<div className="col-5 " align="center">
<h6 id="music-title"><b> { data.artist} - { data.title }</b></h6>
</div>
<div className="col player-col-sm-2" align="center">
<Link to={searchDownloadData} rel=" noopener noreferrer" id="music-download" className="btn btn-outline-primary"><b> MP3 </b></Link>
</div>
</div>
</div>
</>
)
}
)
export default class Top5 extends Component {
render() {
return (
<>
<h2 id="trendtop5" className="trendtop5">Top 10 Trending Bongo Music</h2>
<div id="" className="container"> {newdata} </div>
<div className="container" style={{marginTop: '10px', paddingRight: '10px' }} >
<button className="btn btn-outline-primary" ><NavLink exact to="/artist">Explore More</NavLink></button>
</div>
<br />
</>
);
}
}
Below is my router
<BrowserRouter>
<div id="wrapper">
<header id="header">
<div className="container">
<div id="logo" className="pull-left">
<img id="logo" src={ logo } />
<h1 id="h1home"><strong> Music</strong></h1>
</div>
<nav id="menu-button-nav">
<ul id="nav" className="nav-menu">
<li className="btn btn-warning"><NavLink exact to="/">Home</NavLink></li>
<li className="btn btn-warning"><NavLink to="/justin">Just In</NavLink></li>
<li className="btn btn-warning"><NavLink to="/artist">Artists</NavLink></li>
<li className="btn btn-warning"><NavLink to="/about">About</NavLink></li>
</ul>
</nav>
</div>
</header>
</div>
<div id="content" className="container" >
<Route exact path="/" component={Home}/>
<Route path="/justin" component={Justin}/>
<Route path="/artist" component={Artists}/>
<Route path="/about" component={About}/>
<Route path="/download" component={DownloadArtist}></Route></Route>
</div>
</BrowserRouter>
Below is my Json data that hold the artist details
[
{
"id":1,
"artist": "Artist 1" ,
"title": "tata",
"genre": "rock",
"urldownload" : "https://drive.google.com/uc?export=download&id=1-"
},
{
"id":2,
"artist": "Artist 1" ,
"title": "tata",
"genre": "rock",
"urldownload" : "https://drive.google.com/uc?export=download&id=1-"
},
{
"id":3,
"artist": "Artist 1" ,
"title": "tata",
"genre": "rock",
"urldownload" : "https://drive.google.com/uc?export=download&id=1-"
},
{
"id":4,
"artist": "Artist 1" ,
"title": "tata",
"genre": "rock",
"urldownload" : "https://drive.google.com/uc?export=download&id=1-"
}
]
Download Page
class DownloadArtist extends Component {
render() {
const url = new URL(window.location.href);
const id = JSON.parse(url.searchParams.get("id"));
const artist = url.searchParams.get("artist");
const title = url.searchParams.get("title");
const genre = url.searchParams.get("genre");
const urldownload = url.searchParams.get("urldownload");
console.log(url)
return (
<>
<section>
<h1 id="artistComingSoon" className="center"> ADVERT!!!</h1>
</section>
<section>
<div className="container">
<p> <strong>User ID: </strong>{id} </p>
<p> <strong>Artist Name: </strong>{artist}</p>
<p> <strong>Title: </strong>{title} </p>
<p> <strong>Genre: </strong>{genre}</p>
<p> <strong>Download Link: </strong>{urldownload}</p>
</div>
</section>
<section>
<h1 id="artistComingSoon" className="center"> ADVERT!!!</h1>
</section>
</>
);
}
}
export default DownloadArtist;
Updated
Solved
To handling URL routes in react, we are already use React Router
React Router allow us to manage routes and handling url with dynamic behavior, so that, what we need to do is:
Build route
Build url which its follow this route
For Example:
<Route path={`download/:type`}>
<myComponent />
</Route>
================
<li>
<Link to=`/download/mp3`>Download MP3</Link>
</li><li>
<Link to=`/download/video`>Download Video</Link>
</li>
If you do this, you will send url params and you can fetch it easy by this:
const {type} = useParams();
Your React app, wich is calling the download page, can pass parameter with the url. Your download page then can read those.
You can specify parameter with an "?" in your url. If you want to, you can send multiple parameter as well.
const url = `https://example.com/download/?id=${data.id}`
In your download page you can read those parameter with the URL class.
const url = new URL(window.location.href);
const id = JSON.parse(url.searchParams.get("id"));
With your example it would be something like this.
import React, { Component } from "react";
import {
Route,
NavLink,
HashRouter
} from "react-router-dom";
import "../customcss/style.css";
import data from "../artist/toptrending5.json";
const newdata = data.map((item) => {
const url = `/download/?id=${item.id}`;
return (
<>
<div id="playerbackground" key={item.id} style={{ marginTop: '10px' }}>
<div className="row" align="center">
<div className="col">
<img id="Playericon" src={Playericon} />
</div>
<div className="col ">
<button id="music-play" type="button" className="btn btn-outline-warning"><b>Play</b></button>
</div>
<div className="col-5 " align="center">
<h6 id="music-title"><b> {item.artist} - {item.title}</b></h6>
</div>
<div className="col player-col-sm-2" align="center">
<Link to={url} rel=" noopener noreferrer" id="music-download" className="btn btn-outline-primary"><b> MP3 </b></Link>
</div>
</div>
</div>
</>
)
}
)
export default class Top5 extends Component {
render() {
return (
<>
<h2 id="trendtop5" className="trendtop5">Top 10 Trending Bongo Music</h2>
<div id="" className="container"> {newdata} </div>
<div className="container" style={{ marginTop: '10px', paddingRight: '10px' }} >
<button className="btn btn-outline-primary" ><NavLink exact to="/artist">Explore More</NavLink></button>
</div>
<br />
</>
);
}
}

Vuejs Variable Value Not Changing

I have a vue select component, according to selection I want to change content, and show the loading screen on change event.
<template>
<div>
<div class="row component-separation audit-select">
<div class="col-md-4 pull-right">
<v-select
id="auditModeSelect"
:options="auditOptions"
label="label"
placeholder="Change Audit View Type"
class="form-control border-bottom"
v-model="auditOption"
#input="changeViewMode"
:clearable="false">
</v-select>
</div>
</div>
{{loadingTheContent}}
<div v-if="loadingTheContent">
<loading/>
</div>
<div v-else>
....
</div>
</div>
</template>
changeViewMode(selectedMode) {
this.loadingTheContent = true;
if (selectedMode && selectedMode.value === 1) {
...
} else {
...
}
this.loadingTheContent = false;
},
But loadingTheContent variable value is always false, not changing.
I also tried with adding custom button to trigger but same thing exists