HTML image not loading the image src - html

Hey guys I'm making a TodoApp in react js, and I have a simple layout and I wanted to add a few images to the app. But when I add the images it is not loading that image.
Here is the code
import TodoList from './components/TodoList';
import imagem from './skate.png'
function App() {
return (
<div className="todo-app">
<TodoList />
<img src="imagem"/>
</div>
);
}
export default App;
And here is an image of what´s happening:

When using an bundler (like Parcel or Webpack) to handle images, you need to remember that the imported value is a variable.
You pass variables to props with { and }. Using a pair of " gives you a hardcoded string.
<img src={imagem} />

So,
In React.js (jsx) things don't work quite like HTML. WHat you are doing is importing the image from its location, by using:
import image from './skate.png';
and then, inside of your function.
If you import anything (image, css file, json file), for you to be able to use it you need to call it.
for example:
import JsonData from './data.json'
function App(){
return(
<div>
<JsonData/>
</div>
)
}
To call it.
SO in you case, you just need to replace
to
and it should work.

How about if you do this:
<img src={imagem} />
otherwise, it gets interpreted as a string and you have no http://../imagen on your site.

The problem with your code is that
"imagem"
is read as a String. To read it as an image, place {} around it as so:
{imagem}

"imagem" is string. Need variable {imagem].

when you use qoutes "" in jsx, it consumes it as a string and when you use {}, it consumes it as normal JS, so in your case, if you use
<img src={imagem} />
that would solve your problem

Related

Inject ordered list with innerHTML in Angular

I'm using Angular CLI v13.3.6 with Node v16.12.0 and I've a problem when I use innerHTML property.
I'm using Angular CLI v13.3.6 with Node v16.12.0.
In typescript file I've a variable with an ordered list like this:
let myText = "<ol><li>first</li><li>second</li></ol>";
I need to show this text in a disabled div, so this is the code that I'm using in the html file:
<div id="myId" class="myClass" [innerHTML]="myText" disabled></div>
The result is that the text is shown but the numbers not. The same issue is present when I use the unordered lists. How can I do?
For security reasons, Angular compiler does not accept any string to be injected as HTML. You can bypass this by using DOMSanitizer to "trust" the string and parse it as valid HTML.
You will have to import DomSanitizer and inject it in yopur constructor like:
import { DomSanitizer } from '#angular/platform-browser';
constructor(private readonly domSanitizer: DomSanitizer) { }
And then use DomSanitizer to trust your string to parse it as HTML. You can use like this:
this.domSanitizer.bypassSecurityTrustHtml(YOUR_STRING_HTML);
This has nothing to do with Sanitize html. It is CSS issue.
So to avoid overwritten CSS. You could try:
Creating a brand new angular app: ng new. This way no third party CSS involved
Open the app in Incognito/Anonymous mode, this will help prevent any browser extensions to interfere with your app

Is there literally any way to get whitespace filenames to work with <img src="...">?

I have a file named "Ashen Valley-Thumbnail.jpg".
For my own sanity, I would rather not replace every single space in every single filename manually with a "valid" encoding like %20, which is the only way to fix this outside of writing a program to do it for me (which would take even longer). My goal is to be able to transfer my named files directly into the source folders (with spaces!) without having to rename them.
I've tried literally every trick in the book, namely name_of_file.replace(/ /g, "%20"), putting the name in quotes for the srcurl, and encodeURI(name_of_file), the only three answers the internet seems to have for this question. None of them worked.
I'm using React and Node.js with Express. In my server.js file, I have a fs.readdirSync block that returns all file names in a directory. The function takes the file names and tries to make an <img> from the file name and the path.
There are no errors in my code, so, I don't need to type it out. I just need someone to tell me if what I'm trying to accomplish is at all possible.
EDIT:
Some clarification:
The context I'm using <img src="..."> in:
props.artwork.map(genre => {
return(
<div className = "genre">
<h2 className = "genre-name">{genre.name}</h2>
<hr></hr>
<div>
{genre.array.map(image => {
let name = image.replace(/=|-Thumbnail|.jpg|.png/g, " ");
return (
<div className = "thumbnail">
<img src = {"/images/Artwork/Concept/thumbnails/Ashen Valley-Thumbnail.jpg"} alt = {"" + name + ""}></img> // THIS IS THE PROBLEM AREA *************
<p>{name}</p>
</div>
)
})}
</div>
</div>
)
The src above works when the file name is "Ashen=Valley-Thumbnail.jpg" and I type "Ashen=Valley-Thumbnail.jpg" in the src.
This is in React, part of a functional component's return(...)
Strictly going by your title question. It sounds like you're wondering ...
Is there literally any way to get whitespace filenames to work with
<img src=“…”>
I just tried experimenting within my own local react app by adding a basic jsx image tag to my page.
<img width="300" src={"./images/potter space media.jpg"} alt={'stack-overflow-test'} />
I then dragged a random jpg from my desktop into my project.
I was eventually able to prove that yes, you can render an image that has spaces in its name. I was able to get "potter space media.jpg" to render correctly.
See Example here:
Things to Note:
it matters where you save or store your images. Are you storing them under "./public" vs. "./src" ?
I found this question and answers helpful Correct path for img on React.js
`
You might want to take advantage of modularizing your components. This is an example of what you are trying to do. I would expect this kind of modularity from a professional PR. Otherwise, you may be doing something else fundamentally wrong. Use a custom <Img /> component for your images:
// Modular hook
function useEncodedURI(uri) {
const [encoded, setEncoded] = useState();
useEffect(() => { setEncoded(encodeURI(uri)) }, [uri]);
return encoded;
}
// Replace all <img /> with <Img />
function Img({ src, ...rest }) {
const encodedSrc = useEncodedURI(src);
return <img src={encodedSrc} {...rest} />
}
Don't use <img />. If you want consistency, just replace all <img /> with <Img />. Any decent text editor can swath over this change in a few keystrokes.

Hello i am having trouble getting the location of this picture to show in my react project

Its a JS File (FacePalm) I added the JSX curly braces but it still won't show up.
Here is the fiddle:https://jsfiddle.net/y68h9oj3/
I am trying to add a picture to my react project but it will not show up I tried hosting the picture on a web server it works but when I use local directory the image does not show up.
C:\Users\user\Documents\GitHub\Portfolio\Rework1\src Here is where the pictures location.
here is the src I have on the image tag
<img src="src/Aboutme.png" alt="Aboutme Header"></img>
C:\Users\user\Documents\GitHub\Portfolio\Rework1\src Here is where the pictures location.
<img src="src/Aboutme.png" alt="Aboutme Header"></img>
I expected the image to show up
Try importing your image and then use it with curly braces. Something like this
import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;
Refer https://facebook.github.io/create-react-app/docs/adding-images-fonts-and-files

How can I display image encoded in base64 format in Angular 6?

I struggle with a problem associated with Angular 6 and displaying image encoded in base64 format. Any ideas why code shown below doesn't display image?
html:
<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<img src="{{this.hello}}" />
ts:
this.hello = "data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."
While code shown below works properly and displays picture?
html:
<tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">
<!--<img src="data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."/>
this.hello is assigned in the constructor just for test purpose. I create it in this way this.hello = 'data:image/png;base64, ' + this.UploaderService.imageRecognitionRowsData[0].toString() My main goal is to display imageRecognitionRowsData in this loop <tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows">. So for first iteration I would display image imageRecognitionRowsData[0] then during next iteration image imageRecognitionRowsData[1] etc. The length of this.UploaderService.tableImageRecognition.dataRows is always the same as this.UploaderService.imageRecognitionRowsData When I add <p>{{this.hello}}</p> I get the same string in html.
I have no idea what is wrong. I tried also with this.hello2 = this.sanitizer.bypassSecurityTrustResourceUrl(this.hello);, this.hello2 = this.sanitizer.bypassSecurityTrustUrl(this.hello);, <img [src]="this.hello" /> etc. but nothing works. Any ideas how to solve this?
You don't use "this" to refer the variables defined in the component "ts" file. Remove "this" may solve your problem.
Please Review this stackbliz Fiddle. Look inside the app component to see the implementation.
StackBlitz
This is what worked for me when working with base64 images.
HTML:
<img [src]="currVerifiedLoanOfficerPhoto">
Component:
this.currVerifiedLoanOfficerPhoto = 'data:image/jpg;base64,' + (this.sanitizer.bypassSecurityTrustResourceUrl(item) as any).changingThisBreaksApplicationSecurity;
You don't use this in html templates in Angular. All the variables/member methods are resolved on class by default. Access the variables directly as follows:
<img [src]="hello" />

How to load image (and other assets) in Angular an project?

I'm pretty new to Angular so I'm not sure the best practice to do this.
I used angular-cli and ng new some-project to generate a new app.
In it created an "images" folder in the "assets" folder, so now my images folder is src/assets/images
In app.component.html (which is the root of my application), I put
<img class="img-responsive" src="assets/images/myimage.png">
When I do ng serve to view my web application, the image does not display.
What is the best practice to load up images in an Angular application?
EDIT: See answer below. My actual image name was using spaces, which Angular did not like. When I removed the spaces in the file name, the image displayed correctly.
In my project I am using the following syntax in my app.component.html:
<img src="/assets/img/1.jpg" alt="image">
or
<img src='http://mruanova.com/img/1.jpg' alt='image'>
use [src] as a template expression when you are binding a property using interpolation:
<img [src]="imagePath" />
is the same as:
<img src={{imagePath}} />
Source: how to bind img src in angular 2 in ngFor?
I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.
Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes.
For example :
'my-image-name.png' should be 'myImageName.png'
'my image name.png' should be 'myImageName.png'
If you put the image in the assets/img folder, then this line of code should work in your templates :
<img alt="My image name" src="./assets/img/myImageName.png">
If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.
Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">
Normally "app" is the root of your application -- have you tried app/path/to/assets/img.png?
1 . Add this line on top in component.
declare var require: any
2 . add this line in your component class.
imgname= require("../images/imgname.png");
add this 'imgname' in img src tag on html page.
<img src={{imgname}} alt="">
You can follow the below steps in Angular 8+
Step 1: load the image as below in component
const logo = require('../assets/logo.svg').default as string;
#Component({
selector: 'app-show-image',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class ShowImageComponent implements OnInit {
logo = logo;
constructor() { }
ngOnInit() { }
}
step 2: Add the logic in html file
<img [src]="logo" [alt]="'logo'">
If launched without further configuration, you will see a strange error:
ERROR in src/app/app.component.ts(4,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i #types/node` and then add `node` to the types field in your tsconfig.
Do as suggested – add the #types/node typings to your project by running npm install #types/node and edit tsconfig.app.json to set:
"compilerOptions": {
"types": ["node"],
...
}
For more info
resource
It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).
Example A:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yourpage.html
As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:
<img class="img-responsive" src="../assests/images/myimage.png">
Example B:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yoursubmodule
|__yourpage.html
Here you have to go u in the tree by 2 folders:
<img class="img-responsive" src="../../assests/images/myimage.png">
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
Try not give space while loading the images.
Instead of
<img src='assets/img/myimage.png' alt="">
try with string interpolation or Property Binding to load the source image as best practice.