why image doesn't show up - javascript

I'm trying to feed image path through property path and render it. I have many images and I want to set the image in runtime so I cannot use pre import the image prior to rendering. But the image does not show.
Error: cannot find module (but path is correct)
but when I replace the varible path to actual path as var imageName = require('./Assets/profpicjpg.jpg').default; then image shows up, but I wanna use the variable path to feed the variable path data
Rendering this
import Profpic1 from './Components/Public-page/Profile-card';
function App() {
return (
<div className="App">
<Profpic1
path = './Assets/profpicjpg.jpg'
/>
</div>
)
}
export default App;
Function (this is in a different page)
export default function Profpic1 ({path})
{
var imageName = require(path).default;
return (
<div>
<img src={imageName} />
</div>
)}

Related

React JS: rendering an image from blob

I am trying to render an image on my page by calling an API from a useEffect hook. The service returns a blob, which gets saved in a state. Finally, the state variable is called from an image src attribute.
So far I have tried using the URL.createObjectURL() method in the image src's attribute, but I get the following error.
<img src={URL.createObjectURL(blob)} alt="test image" />
Also I tried converting the blob's string into a blob, then passing it into the URL.createObjectURL() method. The result is an image with an src attribute of blob:https://i86fqf.csb.app/fcab2185-c1b2-4fe7-9c9b-8ca3c56a4467 but the image does not loads.
// Other imports ...
import response from "./response";
export default function App() {
const [imageBlob, setImageBlob] = useState(response);
const blob = new Blob([imageBlob.items[0].image.$content], {
type: "image/jpeg"
});
const imageURL = URL.createObjectURL(blob);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<img src={imageURL} alt="img" />
</div>
);
}
Any idea what I am missing?
You can find a code example here https://codesandbox.io/s/image-blob-not-loading-i86fqf
The '$content' is the base64 string, and if you want to create blob from this, you can study the post here: Creating a BLOB from a Base64 string in JavaScript
Or you can simply add "data:image/png;base64," to make base64 work as src.
const base64 = `data:image/png;base64,${imageBlob.items[0].image.$content}`;
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<img src={base64} alt="img" />
</div>
);

Angular - Use a default image if image does not exist on server

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.
If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.
component.html
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{coverPhoto}}"
(error) ="changeSource($event)" />
</div>
component.ts
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
changeSource(event) {
event.target.src = "https://imageurl";
}
directly use (where defaultImage is a variable in ts file which holds the default image path) -
(error)="$event.target.src = defaultImage"
your HTML -
<div *ngFor="let coverPhoto of coverPhotos">
<img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>
Working example here.
You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -
this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
this.coverPhotos = result;
}, error => {
this.errors = error;
this.changeSource(event);
}, () => {
}
);
The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.
<div>
<img src="{{coverPhotos}}"
(error)="$event.target.src = defaultImage" />
</div>

How to use a HTML portion of a react.js file to another react.js file

I am trying to use the content of a separate react.js file to another react.js file. The js file contains a drop down & the drop down i want to show on the basis of a condition. Below is the js file which contains the drop down
const MyDataTableHeader = ({
first =0,
pageSize=0,
totalElements=0,
exportFile,
})
....
return(
<div className="someCss">
<Dropdown style={{width:100%, textAlign : "center"}}
value={selectedFileFormat}
options = {downloadOptions}
placeholder="Export As"
id={DOWNLOAD_OPTION}
name={DOWNLOAD_OPTION}
onChange={(e) => {
setSelectedFileFormat(e.value);
}}
/>
</div>
<div style={{padding:"1em"}} className = "someCss1">
<Button type="button" icon = "pi pi-download" iconPos="left" onClick={exportHandler}
/>
This portion of the code displays a Drop Down and a option to export, i want to use this code block within another js file , below is the content of the js file
const MySearchPanel = ({onSearch,onClear,exportFile }) =>
const searchHandler = () => {
if(//some Condition){
// i want to show the Drop down with export option here
You want to export your dropdown as a component and then inside your other file inside your condition you just render it using JSX.
import Dropdown from "../from/another/file" // const DropDown = require('from another file') if you do not wish to use module syntax.
const MySearchPanel = ({onSearch,onClear,exportFile }) =>
const searchHandler = () => {
// ...
return (
//if the codition is true show dropdown otherwise show nothing
<div>
{Condition ? <Dropdown /> : null }
</div>
);
// ...
I hope this answers your question.

Using an imported image based on json data character name

I am getting data from a json file and when I get the character name of the object i'd like the div to render an image from an image I had imported. But when I use src={char} and say for example the char from the json file is 'sage' i'd like to use the sage image. But doing this method does not work like that. Also I am successfully getting the data from the json file so no problems on that end.
Thanks!
import sage from '../../assets/images/agents/sage_thumb.webp';
import viper from '../../assets/images/agents/viper_thumb.webp';
import jett from '../../assets/images/agents/jett_thumb.webp';
import valorant_rank from '../../assets/images/ranks/valorant.png';
const renderBody = () => {
return matchData && matchData.map(({ id, char, name, roundsPlayed, performance, multiKills, team }) => {
return (
<tr key={id} className='tr-background'>
<td className='match-table__agent-cell'><img className='img-fluid' src={char} alt="" /></td>
</tr>
)
})
}
I would use an object to map the agent name to its image url
const imageByAgent = {
sage: "../../assets/images/agents/sage_thumb.webp",
viper: "../../assets/images/agents/viper_thumb.webp",
...
}
And for the image src you can fetch the url using the character name
<img className='img-fluid' src={imageByAgent[char]} alt="" />

Trigger .py file when JS page is opened on nodjs server browser

I have a nodjs server set up with several JS pages. On one of them, I want a local .py file to be opened and run one time in the background. I DON'T need to generate a response from it.
I have flask set up already, but I don't understand how to incorporate that with my current React Javascript page (the one I want my python file triggered from).
In different instances, I have tried using:
var path = require('C:/Users/myPath/python.exe');
var nwDir = path.dirname(process.execPath);
var spawn = require("child_process").spawn;
var child = spawn(nwDir + '/test.py');]
as well as:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["/test.py"]);
but I receive this error in both instances:
TypeError: spawn is not a function
located at:
const pythonProcess = spawn('python',["/test.py"]);
lastly I have also tried:
var express = require('express');
var app = express();
const {PythonShell} = require('python-shell');
var options = {
mode: 'text',
pythonPath:
'C:/Users/myPath/python.exe',
pythonOptions: [],
// make sure you use an absolute path for scriptPath
scriptPath:
C:/Users/myPath/test.py', args: []
};
PythonShell.run('test.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during
execution
console.log('results: %j', results);
});
but I receive this error:
TypeError: Cannot read property 'prototype' of undefined
located at my response.js file:
var res = Object.create(http.ServerResponse.prototype);
Is there something I should be including in my server.js file?
Is there a way I can incorporate flask with my current JS page?
For reference, here is a basic version of my current JS file:
myFile.js:
import React from "react";
import Header from "../Header";
import Footer from "../Footer";
class SummaryPage extends React.Component {
render() {
return (
<div>
<Header />
<div className="container-fluid ">
<b><h1>Update and Read CSV File </h1></b>
</div>
<form enctype="multipart/form-data" action="/upload/image"
method="post">
<input type="file" id="fileUpload" />
<div id="dvCSV">
</div>
</form>
<Footer/>
</div>
);
}
}
export default SummaryPage;
To reiterate, how can I have a local .py file be opened and run in the background when my JS page is opened? I would also be happy if it had to occur with the click of a button. No response from the .py file is needed.
Thank you for the time.

Categories