I have a json object which contains html tags in it.I have understood the disadvantage of using dangerouslySetInnerHTML and trying to use parse/stringify instead of it.But I could't convert the object to html tags.I'm not allowed to use any other react packages. So, is there any solution ?
[
{
"category": "Chapter",
"results": [
{
"content": "that <em>cultural</em> tool you don’t do a good job of it. From this perspective, <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em>",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
},
{
"category": "Learning Objectives",
"results": [
{
"content": " <em>culture</em> is a communication.",
"id": "4c00-b7f6-d6e0e252ae9e"
},
{
"content": "sample <em>culture</em> which",
"id": "4c00-b7f6-d6e0e252ae9e"
}
]
}
]
import React from 'react';
import PropTypes from 'prop-types';
const Result = ({ data, onSearchResultClick }) => (<div >
{
data.map((category, index) => (
<div key={index}>
<div key={index}>{category.category}</div>
<hr />
<div className="searchShowData" >
{
category.results.map((result, resultIndex) => (
<p
key={resultIndex}
dangerouslySetInnerHTML={{ __html: (result.content) }}
onClick={() => onResultClick(result.id, result.type)}
/>
))
}
</div>
</div>
))
}
</div>);
Result.propTypes = {
data: PropTypes.array.isRequired,
onSearchResultClick: PropTypes.func.isRequired
};
export default Result;
Related
I have a functional component that looks like this:
import React from 'react'
import PropTypes from 'prop-types'
import Styles from './searchbar.scss'
const AutoFill = (props) => {
const results = props.results || {}
return (
<ul className={Styles.searchUl}>
{Object.entries(results).map(([key, value]) => {
console.log('VALUE', value)
console.log('VALUENAME', value.apple.name)
return (
<li className={Styles.searchLi}>
<a className={Styles.searchA} href={value.apple.href} target='_blank' rel='noopener noreferrer' key={value.href}>
{value.apple.name}
</a>
</li>
)
})}
</ul>
)
}
AutoFill.propTypes = {
results: PropTypes.array
}
export default AutoFill
I also have a Json file that looks like this:
{
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
With console.log('Resultsssssss', (results[key].apple.name)) i get the specified name of apple only which returns obv apple.
So i want to know how i can return the name of all the objects at once, To show them in a UL under a searchbar for a autoFill when typed a everything of a should appear as suggestions: https://gyazo.com/006e856190e8e063934a07eb0725926e
Any answer will be highly appreciated and looked into.
First, you want to get all the values of the object. Object.values(results) will return an array that looks like this:
[
{
"name": "apple",
"href": "https://www.apple.com/"
},
{
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
{
"name": "box",
"href": "https://www.box.com/"
},
{
"name": "berserk",
"href": "https://www.berserk.com/"
}
]
Now you can use map to get the names: Object.values(results).map(x => x.name). This will return an array of names: ['apple', 'armadillo', ...].
When you passed 2 arguments in your map function, first one is general key of your json file, results in your case and second argument is content under this key.
Try this:
const AutoFill = (props) => {
const results = props.results || []
return (
Object.entries(results).map(([name, content]) => {
for (const key in content) {
if (content.hasOwnProperty(key)) {
console.log('Resultsssssss', (content[key].name))
}
}
})
)
}
You can simply return all properties within from within the map function without the for loop which you have in your code
const data = {
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
const res = Object.entries(data.results).map(([key, value]) => {
return value.name;
});
console.log(res);
What you need for render is to restructure your HTML a little bit
const data = {
"results": {
"apple": {
"name": "apple",
"href": "https://www.apple.com/"
},
"armadillo": {
"name": "armadillo",
"href": "https://www.armadillo.com/"
},
"box": {
"name": "box",
"href": "https://www.box.com/"
},
"berserk": {
"name": "berserk",
"href": "https://www.berserk.com/"
}
}
}
const Styles = {}
const AutoFill = (props) => {
const results = props.results || {}
return (
<ul className={Styles.searchUl}>
{Object.entries(results).map(([key, value]) => {
return (
<li className={Styles.searchLi}>
<a className={Styles.searchA} href={value.href} target='_blank' rel='noopener noreferrer' key={value.href}>
{value.name}
</a>
</li>
)
})}
</ul>
)
}
ReactDOM.render(<AutoFill results={data.results} />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app" />
I try to pass a JSON as String from my Spring Controller to the React Frontend.
JSON:
{
"name": ".",
"size": 0,
"children": [
{
"name": "setup.bat",
"size": 6,
"children": []
},
{
"name": "src",
"size": 0,
"children": [
{
"name": "main",
"size": 0,
"children": [
{
"name": "java",
"size": 0,
"children": [
...
I try it with Thymeleaf and the console output on my site worked:
index.html
$( document ).ready(function() {
var jsondata = /*[[${jsondata}]]*/;
console.debug(jsondata);
});
but now i try to used it in react I get an error:
app.js:
class App extends Component {
render() {
return(
<div>
{jsondata}
</div>
)
}
}
Uncaught ReferenceError: jsondata is not defined
What is the Problem in React ?
Set and access the JSON on directly on the window object.
window.jsondata = /*[[${jsondata}]]*/;
class App extends Component {
render() {
return(
<div>
{window.jsondata}
</div>
)
}
}
Solution:
I can use the Javascript var with my React code, but the Problem was in my html file. I make a wrong order of the scripts.
If i use the React bundle at the end it works:
index.html:
<script th:inline="javascript">
var jsondata = /*[[${jsonHierarchy}]]*/;
console.log(jsondata);
</script>
<script src="/bundle.js"></script>
I am working on angular 2 Tabs component.
Currently i am following below Plunker example
Angular 2 Tabs
I need to make Tabs dynamic by reading the Local JSON file.
My JSON
[
{
"id": "1",
"name": "General",
"content": [
{
"header": "Basic Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
},
{
"id": "2",
"name": "Additional info",
"content": [
{
"header": " Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
}
]
Service.ts
export class DashboardService{
private _url: string = "assets/sample.json";
constructor( private _http: Http){}
getRecords(){
return this._http.get(this._url)
.map((response:Response) => response.json())
.catch(this._errorHandler);
}
_errorHandler(error: Response){
console.error(error);
return Observable.throw(error || "Server Error");
}
}
Component.ts
export class DynamicTabsComponent implements OnInit{
records = [];
errorMsg: string;
constructor(private _dashboardService: DashboardService) { }
ngOnInit() {
this._dashboardService.getRecords()
.subscribe(
resGetRecords => this.records = resGetRecords,
resRecordsError => this.errorMsg = resRecordsError
);
}
}
Now how to read it in the component file.
here in tab link, i am expecting is
Additional info
General
Description required with header and label.
Any help would be appreciated.
You do an *ngFor on your json to display the tabs:
<tabs>
<tab *ngFor="let tab of tabs" tabTitle="{{tab.name}}">
<div>{{tab.content[0].header}}</div>
<div>{{tab.content[0].contents[0].label}}</div>
</tab>
</tabs>
You declare your json into the component or import it from outside:
class App {
tabs = [
{
"id": "1",
"name": "General",
"content": [
{
"header": "Basic Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
},
{
"id": "2",
"name": "Additional info",
"content": [
{
"header": " Information",
"contents": [
{
"label": "Report goes here"
}
]
}
]
}
];
}
Working fork of your plunker here
If it's a local JSON file, why are you making http calls ?
To read a JSON file, simply do
let jsonFile = require('relative/path/to/json/file.json')
And it should load your JSON file.
Using React I am trying to pass down a parsed JSON file and map through the object. However seeing as it is an object I can only map the object using Object.keys as below:
const question = Object.keys(questions).map((data, index) =>
<QuestionList questions={data} key={index} />
However using this I am only able to access the top level of my data structure. So using this code and passing down my object. Using Object.keys() I can only access "questions" or "q1" or type, text, qId etc. I can not pass all object properties at once and specify what I need in a child component.
"questions": {
"q1": {
"qId": "1",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
},...
What would be the easiest way to pass the whole object with child properties so I can use these in a child component? do I have to use something other than props?
const questionObjects = Object.values(JSON.stringify(theJSONinYourQuestion));
const questionComponents = questionObjects.map(question => <Question qId={question.qId} />);
Basically, use Object.values instead of Object.keys, and you've got a nice array of questions you can use.
Edit: if you don't have Object.values available in your environment (it is experimental)
const originalQuestions = JSON.stringify(theJSONinYourQuestion);
const questionKeys = Object.keys(orginalQuestions);
const questionObjects = questionKeys.map(key => originalQuestions[key]);
...
You can maintain access to the question object inside of a .map by assigning it to a variable outside that scope. Here's a jsBin showing the idea
const objectOfQuestions = {
"questions": {
"q1": {
"qId": "1",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
},
"q2": {
"qId": "2",
"type": "YN",
"text": "Text 1",
"tip": {
"logo": "assets/icons/gadgetz.svg",
"logofallback": "assets/img/gadgetz.png",
"heading": "Heading 1",
"text": "Text 2"
}
}
}
}
const Question = ({ id, question }) => {
return (
<div>
<h1>Question: {id}</h1>
<p>id: {question.qId}</p>
<p>type: {question.type}</p>
<p>text: {question.type}</p>
</div>
)
}
const QuestionList = ({ questions }) => {
const questionObj = questions;
return (
<div>
{Object.keys(questions.questions).map((key, i) => {
return (
<div key={key}>
<Question id={key} question={questionObj.questions[key]} />
</div>
);
})}
</div>
);
}
ReactDOM.render(<QuestionList questions={objectOfQuestions} />, document.getElementById('app'));
I am new to react. I am using an api in the form of
{
"category": "dogs",
"available": [
{
"name": "pedro",
"breed": "chihuahua"
},
{
"name": "roxane"
"breed": "beagle"
}
]
},
{
"category": "cat",
"available": [
{
"name": "garfield",
"breed": "tobby"
}
]
}
I want to display ALL the pets available from the same category in name-breed pairs.
Example: Display all dogs
Pedro
Chihuahua
Roxane
Beagle
but that array is giving me hard times.
Attempt
App.jsx
{this.state.data.map((availablePets, i) => <Content key = {i} data = {Content} />)}
Content.jsx
{this.props.data.available[WhatDoIPutHere?].name}
{this.props.data.available[ajsnxnnx].breed}
Is there another way to display ALL the available pets from the same category in name-breed pairs?
SOLVED
{this.props.data.faqs.map((QA,i) =>
<div key={i}>
<h4>{this.props.data.category[i].name}</h4>
<p>{this.props.data.category[i].breed}</p>
</div>
)}
Your solution is not dynamic.
This will be a better solution.
{
this.props.data.faqs.map((QA,i) => {
const pets = QA.available.map((pets, j) => {
return <div key={j}
<h4>{pets.breed}</h4>
<p>{pets.name}</p>
</div>
})
return <div key={i}>
<h4>{QA.category}</h4>
{pets}
</div>
})
}