How to show a image in React from a JSON file - javascript

// JSON File
{
"project": [
{
"id": "0",
"title": "Old Portfolio",
"images" :{
"main": "portfolio.png",
"second": ""
},
"content": ["This is one of my first few projects I made as a beginner", "At this project, I learned using JavaScript for making interactive elements like a navbar button. This project was not really something I'm proud of. Hence why I'm making a new portfolio but now with react"]
,
"tags": ["HTML5", "CSS", "JavaScript", "jQuery"]
},
{
"id": "1",
"title": "Twitter Clone",
"images" :{
"main": "twitter_clone.png",
"second": ""
},
"content": ["Project I made to improve my skills in PHP and MySQL.", "At this project, I used MySQL to store data and use PHP to alter what my website will show to the user. I've also used AJAX and JQuery for processing data from MySQL with PHP."]
,
"tags": ["HTML5", "CSS", "JavaScript", "PHP", "MySQL", "jQuery", "AJAX"]
}
]
}
// projectList is from a JSON file
// ProjectList.js
{projectList.map((project) => (
<Projects key={project.id} projectData={project}/>
))}
// Projects.js
const imagePath = "../images/";
const mainImage = imagePath + projectData.images.main
const Projects = ({projectData}) => {
<img style={{
width: "100%",
}} src={mainImage}alt="" />
}
<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>
I have a JSON file that stores the images. This is gonna be for a list of projects.
The image src is not working and I can't import an image inside the function.
I hope someone could help I am new to React

JSON should not be object, I guess in this case you can use array.
instead of using "img" you must use thumbnail, cause your object(project) has no "img" key, but has "thumbnail"->
const mainImage = imagePath + projectData.thumbnail.main
// JSON File
[
{
"id": "0",
"title": "Old Portfolio",
"thumbnail" :{
"main": "portfolio.png",
"second": ""
},
"content": ["This is one of my first few project I made as a beginner", "At this project I learned using JavaScript for making interactive elements like a navbar button. This project was not really something I'm proud of. Hence why I'm making a new portfolion but now with react"]
,
"tags": ["HTML5", "CSS", "JavaScript", "jQuery"]
},
{
"id": "1",
"title": "Twitter Clone",
"thumbnail" :{
"main": "twitter_clone.png",
"second": ""
},
"content": ["Project I made to improve my skills in PHP and MySQL.", "At this project I used MySQL to store data and use PHP to alter what my website will show to the user. I've also used AJAX and JQuery for processing data from MySQL with PHP."]
,
"tags": ["HTML5", "CSS", "JavaScript", "PHP", "MySQL", "jQuery", "AJAX"]
}
]
// projectList is from a JSON file
// ProjectList.js
{projectList.map((project) => (
<Projects key={project.id} projectData={project}/>
))}
// Projects.js
const imagePath = "../images/";
const mainImage = imagePath + projectData.thumbnail.main
const Projects = ({projectData}) => {
<img style={{
width: "100%",
}} src={mainImage}alt="" />
}
<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>

I finally found a way,
I put the images on the public folder "public/images/image.png"
and
const Projects = ({projectData}) => {
<img src={`images/${projectData.images.main}`}/>
}

Related

How to show the images of card components that exist outside the src folder in ReactJs?

I have a react app which integrated with FastAPI and MongoDB. In my project, there is a page to show some information as cards. These cards contain images, but those images are generated automatically in the backend folder. Each card contains the path of its own picture, but when I call this path in the component, it doesn't show the picture as illustrated in the picture 1.
Note: I used React component class format to build my project!
Here is how each card is generated:
renderCard(card, index) {
return (
<Card key={index} className="box">
<Card.Img className="bodyImg" variant="top" src={card.coverPic} />
<Card.Body className="bodytext">
<Card.Title>{card.name}</Card.Title>
<Card.Text>{card.Placename}</Card.Text>
<Card.Text>{card.setting}</Card.Text>
<Link
to={{
pathname: "/CardInfo",
state: card,
}}
style={{ textDecoration: "none" }}
className="buttonStyle"
>
Show
</Link>
</Card.Body>
</Card>
);
}
Here is the information for two cards:
First card:
{
"_id": {
"$oid": "60fd0c3b3d4412b25bea49e7"
},
"name": "Test the coverPic",
"path": [
"C:/Users/Asma/Desktop/Projects/backend/app/videos/HaramCovid2.mp4"
],
"Placename": "Makkahh",
"setting": "Public Place",
"country": "Saudi Arabia",
"duration": "1",
"date": "2021-06-29",
"sendEmail": true,
"publish": true,
"outputVideoPath": "output/Test the coverPic.avi",
"contactRate": 1,
"userId": "60fbffa2e7db6bc44a842ea6",
"framesPath": "C:/Users/Asma/Desktop/Projects/backend/app/videos/output/",
"coverPic": "C:/Users/Asma/Desktop/Projects/backend/app/videos/output/Test the coverPic-30.png"
}
Second card:
{
"_id": {
"$oid": "60fc79bbac4f82a891c01ef2"
},
"name": "testing",
"path": [
"C:/Users/Asma/Desktop/Projects/backend/app/videos/HaramCovid2.mp4"
],
"Placename": "Haram",
"setting": "Mass Gathering",
"country": "Åland Islands",
"duration": "1",
"date": "2021-07-02",
"sendEmail": false,
"publish": false,
"outputVideoPath": "output/testing.avi",
"contactRate": 1,
"userId": "60fc79a0ac4f82a891c01ef1",
"framesPath": "C:/Users/Asma/Desktop/Projects/backend/app/videos/output/",
"coverPic": "output/testing-30.png"
}
AFAIK you cannot use files from outside the src folder. I guess that has some security reasons. You could try to create a symlink or hardlink. It's a link to another file or directory that can be created inside your src folder.
Open a cmd window and navigate to the folder of your choice inside your src folder, e.g. images.
Execute mklink /h HaramCovid2.mp4 "C:/Users/Asma/Desktop/Projects/backend/app/videos/HaramCovid2.mp4" to create a hard link.
JSON:
"path": ["./images/picture1"],
EDIT: Changed the mklink command. Please try this one.

Filter JSON Array in ReactJS component

I am new to the community and English is not my native language (I speak Spanish), but I will try to ask my question as clearly as possible.
I'm learning React and I am working on a component that imports a JSON file containing an array. I'm trying to figure out how to filter the array to be able to show information according to the url patch.
File React:
import React from 'react';
import Lista from '../../Arrays/Lista';
const Card = ({ match }) => {
const product = Lista.filter( p => p.id === parseInt(match.params.id))
return (
<div>
<h1> {product.title} </h1>
<p>{product.description}</p>
<img src={product.image} alt="imagen"/>
</div>
)
}
export default Card;
File JSON:
[
{
"id": 0,
"title": "FunkoPop Woody",
"description" : "FunkoPop Woody Edicion Limitada",
"price": "11.900",
"image": "https://ripleycl.imgix.net/https%3A%2F%2Fs3.amazonaws.com%2Fimagenes-sellers-mercado-ripley%2FImagenes-MIRAKL%2FMPM00002571116%2FMPM00002571116-1-F.jpg?w=750&h=555&ch=Width&auto=format&cs=strip&bg=FFFFFF&q=60&trimcolor=FFFFFF&trim=color&fit=fillmax&ixlib=js-1.1.0&s=95653b7ade9c0f60337f9b396fc0b544"
},
{
"id": 1,
"title": "FunkoPop Stitch",
"description" : "FunkoPop Stitch Regular Edition",
"price": "9.900",
"image": "https://www.tiendawabro.com.ar/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/2/3/2353.jpg"
},
{
"id": 2,
"title": "FunkoPop Jinx",
"description": "FUnkoPop League of Legends",
"price": "10.900",
"image": "https://www.metalgame.cl/wp-content/uploads/2018/01/889698103053.jpg"
}
]

How to build treeviewer from an XML file without AJAX

I need to build a treeview from an XML file. I don't want to use AJAX, as I can simply read the file from my disk (I'm building this app on Electron)
fs.readFile('./xmlfile.xml', function(err, data) {};
Is there anyone that could guide me how to build a tree of an custom made XML file? Basically I'd like to be able to build a tree from any XML data I put into my file.
I've already tried using JStree, but I keep having the same issue with it - it doesn't spit any errors in the console and prints a blank page.
testData is where keep my xmlfile.xml (file is definetely valid and it prints correctly when I put it through console log)
$(document).ready(function() {
// NeDB - Database init
var Datastore = require('nedb');
var fs = require('fs');
fs.readFile('./xmlfile.xml', function(err, testData) {
$('#cRIO_tree')
.jstree({
"core": {
"animation": 0,
"check_callback": true,
"icon": "../assets/tree.png",
"themes": {
"stripes": true
},
"xml_data": {
"data": testData,
"progressive_render": "true"
},
},
"dnd": {
"always_copy": true
},
"types": {
"#": {
"max_children": 1,
"max_depth": 10,
"valid_children": ["root"]
},
"root": {
"valid_children": ["default"]
},
"default": {
"icon": "glyphicon glyphicon-tree-deciduous",
"valid_children": ["default", "file"]
},
"file": {
"icon": "glyphicon glyphicon-flash",
"valid_children": []
}
},
"plugins": ["contextmenu", "dnd", "search", "state", "types",
"sort", "wholerow", "themes", "xml_data"]
})
}
}
Problem is that no matter what I put into my xml - it simply doesn't print it. I even tried examples from
https://old.jstree.com/documentation/xml_data
<!-- FLAT -->
<root>
<item id="root_1" parent_id="0" state="closed">
<content>
<name><![CDATA[Node 1]]></name>
</content>
</item>
<item id="node_2" parent_id="root_1">
<content>
<name><![CDATA[Node 2]]></name>
</content>
</item>
</root>
and that doesn't seem to be working..

Unable to add video into FlatFeed in React Native [GetStream.io]

I'm attempting to incorporate video into a flat feed from GetStreamIO. My current approach is to embed a video element from Expo into the content body of the Activity UI component if the post has a video link. Starting with Youtube links only. I'm running into an issue where I'm not able to select the video url when it's available nested in props.activity.attachments. For some reason I cannot directly access the object in the videos array directly without converting the value to JSON. I referenced this StackOverflow Post for the JSON workaround.
My code to check if attachment has video url and grab it if it does
const LikeActivity = (props) => {
if (props.activity.attachments != undefined) {
console.log(props.activity.attachments)
console.log(fetchFromObject(props.activity.attachments, "og"))
var og = fetchFromObject(props.activity.attachments, "og")
var videos = fetchFromObject(og, "videos")
console.log(og)
// Can get the og object but cannot pull video url from it.
}
return (
<Activity
{...props}
Footer={
<View>
// For Now just putting this here to see the video element render. Need to pass URI from Post to element eventually.
<Video
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
isLooping
style={{ width: 300, height: 300 }}
/>
<LikeButton {...props} />
</View>
}
/>
);
};
My App implementation
<StreamApp
apiKey="XXXX"
appId="XXXX"
token="XXXXXX"
>
<FlatFeed
feedGroup="timeline"
userId="user-one"
Activity={LikeActivity}
/>
</StreamApp>
Fetch From Object method
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
The feed consists of a number of posts and the props.activity.attachments has the following values at runtime. Each post with a link currently has a rich snippet. The attachments value also recognizes videos vs images. I've also included an image of the feed here as a reference.
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://www.rollingstone.com/wp-content/uploads/2018/08/GettyImages-1020376858.jpg",
},
],
"title": "'Queen' rapper rescheduling dates to 2019 after deciding to “reevaluate elements of production on the 'NickiHndrxx Tour'",
"url": "https://www.rollingstone.com/music/music-news/nicki-minaj-cancels-north-american-tour-with-future-714315/",
},
}
undefined
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://images.wsj.net/im-21927/TOP",
},
],
"title": "How to Pair Neutrals and Bright Colors",
"url": "https://graphics.wsj.com/glider/marketreport-4a039902-7e0d-4631-ab83-6cc1931c1bc6",
},
}
undefined
Object {
"og": Object {
"description": "Serial entrepreneur Elon Musk wants to fundamentally change the way we live. But his path to success has been characterized by both great accomplishments and flirtations with failure.",
"images": Array [
Object {
"image": "https://static01.nyt.com/images/2018/08/22/us/19xp-musk-vid-2/19xp-musk-vid-2-videoSixteenByNine1050.jpg",
},
],
"title": "Elon Musk’s Highs and Lows: PayPal, SpaceX, Tesla",
"url": "https://www.nytimes.com/video/business/100000006060092/elon-musk-tesla-spacex.html",
},
}
undefined
Object {
"og": Object {
"description": "We are in a Simulation - Elon Musk",
"images": Array [],
"site_name": "YouTube",
"title": "We are in a Simulation - Elon Musk",
"type": "video.other",
"url": "https://www.youtube.com/watch?v=xBKRuI2zHp0",
"videos": Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
],
},
}
Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
]
Object {
"images": Array [
"https://cdn.vox-cdn.com/thumbor/OBDFDT9j-nHEpGLckE4u5ibX2qU=/1400x1400/filters:format(png)/cdn.vox-cdn.com/uploads/chorus_asset/file/13589869/edu_distance_to_the_moon.png",
"https://www.jpl.nasa.gov/images/mars/20170622/PIA01466-16.jpg",
"http://cdn.sci-news.com/images/enlarge4/image_5608_2e-Jupiter.jpg",
"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/07/SolarFull_SeanDoran_2880FullwidthLede-2880x1620.jpg",
],
}

Backbone application with routes from a static json file (read-only)?

I'm building a read only backbone app with data (sourced from a single static json file) that follows a building/campus structure of sort. That is:
[{
"name": "Building Name",
"id": "building",
"floors":[{
"name":"Ground Floor",
"rooms":[{
"name": "Room 1"
},
{
"name": "Room 2"
}]
},
{
"name":"First Floor",
"rooms":[{
"name": "Room 3"
},
{
"name": "Room 4"
}]
}]
},
{
"name": "Another Building",
"id": "building_2",
"floors":[{
"name":"Ground Floor",
"rooms":[{
}]
},
{
"name":"First Floor",
"rooms":[{
}]
}]
}]
I currently have a basic app set up that shows the list of buildings and floors for each building on a default '' route.
I would like to use the router so that APP/#buildingId/ shows the list of floors for a building with 'buildingId' and APP/#buildingId/#floorId shows the relevant list of rooms, etc.
JSBIN of my current code (without data.json) - http://jsbin.com/welcome/5850/edit
Lots of code is probably obsolete, but I was trying different ways to structure the models/collections. This app will never be more than read-only which is why I went with a static file.
Similar problem: How to use JSON to power interactive Backbone.js app
The solution presented doesn't use the Router at all.
Is this what you are asking for?:
// code simplified and no tested
App.Router = Backbone.Router.extend({
routes: {
"/APP/:buildingId/:floorId": "showRooms",
"/APP/:buildingId": "showFloors"
},
showRooms: function( buildingId, floorId ) {
// code to show the rooms
},
showFloors: function( buildingId ) {
// code to show the floors
},
});
Or am I missing something?

Categories

Resources