React react-icons-kit and get Icons dynamically - reactjs

How to get Icons dynamically in React using extension React Icon kit? I try to find out the way to add a icon dynamically in a MAP-loop as I get them from array "sociallinks"
here is the part of the code
....
import { Icon } from 'react-icons-kit'
import {facebook} from 'react-icons-kit/feather/facebook';
import {instagram} from 'react-icons-kit/feather/instagram';
import {twitter} from 'react-icons-kit/feather/twitter';
....
// dynamic array from redux store
"sociallinks": [
{
"_id": 1,
"type": "facebook",
"linkname": "Facebook",
"link": "https://www.facebook.com/zzzzz/"
},
{
"_id": 2,
"type": "instagram",
"linkname": "Instagram",
"link": "https://www.instagram.com/yyy/"
},
{
"_id": 3,
"type": "twitter",
"linkname": "Twitter",
"link": "https://twitter.com/xxx"
},
{
"_id": 4,
"type": "youtube",
"linkname": "Youtube",
"link": "https://www.youtube.com/user/youtube"
}
]
// problem is here how to markup icon = {xxxxx} from map item.type? item.link and item.linkname works fine.. but not item.type :(((
<ul>
{this.props.data.socialLinks.map((item,i) => (
<li key = {i}> <a href = {item.link}><Icon size={18} icon={item.type} />{item.linkname}</a></li>
))
}
</ul>

Related

Having problems parsing json complex data in react js. Map error

App.js
I am facing this issue file error - Uncaught TypeError: items.data.map is not a function. I have tried some other options but did not work. I cant seem to find what I am doing wrong.
.then((res) => res.json())
.then((json) => {
this.setState({
items: json,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Loading data ... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.data.map((item) => (
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
))
}
</div>
);
}
}
export default App;
JSON Data
Nested API data from json data type.
{
"data": {
"data": [
{
"project_id": "xxxx",
"title": "xxx34",
"description": "xxx23",
"expense": 1699126,
"budget": 6418516,
"country": "xxx",
"sector": [
{
"name": "Accelerate structural transformations",
"code": "18"
}
],
"sdg": [
{
"name": "Peace, justice, and strong institutions",
"id": "16"
}
],
"signature_solution": [
{
"name": "Strengthen effective, inclusive and accountable governance",
"id": "2"
}
],
"donor": [
"Australian DFAT",
"GLOBAL FUND TO FIGHT AIDS, TUBERCULOSIS",
"UNITED NATIONS DEVELOPMENT PRO"
],
"marker": [
"Hows",
"Joint Programme",
"Partner",
"Whos",
"COVID-19 Response"
]
},
{
],
"links": {
"next": null,
"previous": null
},
"count": 44
},
"status": 200,
"success": true
}
I tried data.data.map but still facing the same error. What am I doing wrong here?
Firstly, the TypeError you got is syntax error. The implementation of an arrow function must follow by curly brackets
items.data.map((item) => (
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
))
to
items.data.map((item) => {
<ol key = { item.data} >
Continents: {item.data[0]}
</ol>
})
Secondly, items you are mapping is a nest of JSON object - key: value pair. It's not suitable for mapping.
The mapping iterator or iterating an array is perfect when used to retrieve
data from a sequence item have the same or similar structure.
E.g:
const arr = [{"id": "1", "name": "a"}, {"id": "2", "name": "b"}, {"id": "3", "name": "c"}];
arr.map((item) => {
console.log(item.id);
console.log(item.name);
})
You should pretreat your data first.

making dynamic route by API with next+react

i'd like to make a dynamic route with react and next.js
I have an API like this.
[
{
"id": 1,
"name": "books",
"pages": "277",
"title": "Book A",
"no": 88
},
{
"id": 2,
"name": "books",
"pages": "90",
"title": "Book B",
"no": 32
},
{
"id": 4,
"name": "books",
"pages": "184",
"title": "Book C",
"no": 89
}
...
]
and this API will show in the screen like this. this is mapped li in Book.jsx
<li>
<p>{book.name}</p>
<p>{book.pages}</p>
</li>
Now, what i want to make is when i click li, it connects to the "no" of API and make a new window.
so I created [bookNo].jsx and the same location with pages > index.jsx and added these to [bookNo].jsx
const DetailedView = () => {
const router = useRouter();
const {bookNo} = router.query;
return (
<div>
<p>{bookId}</p>
</div>
);
};
to make router works, i added these code to Book.jsx
useEffect(() => {
getBooks().then(res => {
const book = res.data.DATA.RESPONSE.BOOKS;
for (let i = 0; i < book.length; i++) {
const bookNo = bookData[i].no;
}
}).catch(e => {
console.log(e)
})
}, [])
<Link href="pages/bookView/[bookId]" as={`/bookView/${bookId}`}>
<li onClick>
<p>{book.name}</p>
<p>{book.pages}</p>
</li>
</Link>
And I've got 2 errors that
ReferenceError: bookNo is not defined and router is not working at all.
Can anyone help me with this problem?

How to render image from data object? (React)

guys!
I have object with images.
I need to go through the object and render images from there. (I will have plenty of them).
Here is my js file:
const myJson = {
"data": [
{
"id": 1,
"name": "Landscape of Saint-Remy",
"path": "./a.jpg",
"cost": 400,
},
{
"id": 2,
"name": "Landscape of Saint-Remy",
"path": "./b.jpg",
"cost": 400,
},
{
"id": 3,
"name": "Landscape of Saint-Remy",
"path": "./c.jpg",
"cost": 400,
},
]
}
export default myJson;
I try to render it in my Home component like this:
import React from 'react';
import myJson from '../../server/myJson';
function Home() {
return (
<div>
<Hi />
{myJson.data.map(key => (
<img src={require(`${key.path}`)} key={key} />
))}
</div>
)
But got an error: Module can't be found.
If I render images like this:
<img src={key.path} key={key} />
I see 200ok, but no image because I need to import it and that is why I used require to import image and use it. But it's not working.
Please, help me!
This is not the way to import images, you need to config you webpack and add file-loader or url-loader to require images inside your javascript.
Take a look at this answer:
https://stackoverflow.com/a/37673142/5497628
Here this is how you can do it
const myJson = {
"data": [
{
"id": 1,
"name": "Landscape of Saint-Remy",
"path": require("./a.jpg"),
"cost": 400,
},
{
"id": 2,
"name": "Landscape of Saint-Remy",
"path": require("./b.jpg"),
"cost": 400,
},
{
"id": 3,
"name": "Landscape of Saint-Remy",
"path": require("./c.jpg"),
"cost": 400,
},
]
}
export default myJson;
This is how you have to prepare json data.
import React from 'react';
import myJson from '../../server/myJson';
function Home() {
return (
<div>
<Hi />
{myJson.data.map(key => (
<img src={key.path} key={key} />
))}
</div>
)
This is how you can render it.

React reading nested JSON data fails when loads or refresh

I am developing a screen to show data based on search results. Below is the JSON output.
When I click search result below component is called. In the result screen i need id, name and table1, table2 data.
Table1 and Table2 are nested outputs and these will be displayed in React Table or Data Grid (next step)
Issue: Unable to render StudyData.table1.name
Options Tried
1. UseEffect()
UseEffect() able to read StudyData.studyname but not StudyData.table1.name
Assigned to a variable
Assigned to a state
2. Render
tried using map for subdocuments
Finding: It fails only first time load and refresh. I tried to comment -> save->load -> remove the comments and save. Then works (as component is loaded). I am missing something during the first time load or refresh. Please help
[
{
"id": "DD3",
"studydate": "DDD",
"studydescription": "DD3 Description",
"studyname": "DD3",
"table1": [
{
"no": "1",
"name": "DD3 Name",
"date": "Krishna",
"description\r": "1111\r"
},
{
"no": "2",
"name": "DD3 Nam2",
"date": "Test2",
"description\r": "2222\r"
},
{
"no": "3",
"name": "DD3 Name3",
"date": "Test3",
"description\r": "3333"
}
],
"table2": [
{
"No": "2",
"Study Field1": "21",
"Study Field2": "22",
"Study Field3\r": "23"
}
],
"table3": [
{
"No": "3",
"Study Field5": "T31",
"Study Field6": "T32",
"Study Field7": "T33",
"Study Field 8\r": "T34"
}
],
"_rid": "QeNcANZFTTIKAAAAAAAAAA==",
"_self": "dbs/QeNcAA==/colls/QeNcANZFTTI=/docs/QeNcANZFTTIKAAAAAAAAAA==/",
"_etag": "\"33002e92-0000-0200-0000-5fa6fe320000\"",
"_attachments": "attachments/",
"_ts": 1604779570
}
]
COMPONENT CODE
import React, { useEffect } from "react";
import api from "./UploadStudyFilesapi";
import { DataGrid } from "#material-ui/data-grid";
export default function StudyDisplay(props) {
let myData = props.Study;
const [StudyData, setStudyData] = React.useState([]);
const [Table1Rows, setTable1Rows] = React.useState([]);
useEffect(() => {
// Update the document title using the browser API
api.getStudy(myData.studyname).then((json) => setStudyData(json));
console.log(StudyData.studyname); //works
//console.log(StudyData.table1.no) //doesn't work
let myTable = StudyData.table1;
console.log(myTable);
setTable1Rows(StudyData.table1);
console.log(Table1Rows);
}, [myData]);
return (
<div>
{StudyData.length === 0 ? (
<h1>Loading...</h1>
) : (
StudyData.map((item) => (
<div key={item.studyname}>
{item.studyname}
{/* DOESNT WORK first brose or refresh*/}
{item.table1.map((key2) => (
<div>
{console.log(key2.name)}
{key2.name}
{/* Want to pass Key2 to DataGrid or React-Table */}
{/* <DataGrid rows={key2} columns={{field1:"No"}} /> */}
</div>
))}
</div>
))
)}
</div>
);
}
Thanks for your support. I added conditional rendering based on search selection in parent component. That resolved all the issues

How do I iterate over a JSON file in react?

I'm new to React and for the life of me cannot figure this out.
I have a JSON file (Fontawesome icons):
{
"icons": [
{
"name": "Glass",
"id": "glass",
"unicode": "f000",
"created": 1,
"filter": [
"martini",
"drink",
"bar",
"alcohol",
"liquor"
],
"categories": [
"Web Application Icons"
]
},
{
"name": "Music",
"id": "music",
"unicode": "f001",
"created": 1,
"filter": [
"note",
"sound"
],
"categories": [
"Web Application Icons"
]
},
// etc
To start with I just want to return the name of each icon.
I've been trying to follow various tutorials and have:
import React, { PureComponent } from "react";
import iconList from './services/iconList';
export default class App extends PureComponent {
render() {
const items = iconList.map(data=>{
return(
<div>
<ul>
<li>
<span>{data.name}</span>
</li>
</ul>
</div>
)
})
return items;
}
}
But I get the error: .map is not a function.
I'm not sure what I can do differently. Each tutorial I see seems to use the map function. Is there a better/different way?
Try using
const items = iconList.icons.map(data=>{
Your data is an object with an icons property in it. You can also destructure your iconList when you import:
import {icons as iconList } from './services/iconList';

Resources