import mainSampleImg from 'images/my_img.jpg';
class ImageCard extends Component {
imgDiv = React.createRef();
componentDidMount() {
if (this.props.bgImgPath) {
const image = new Image();
var test={mainSampleImg}; # the value of test is {"mainSampleImg": "my_img.jpg?1ecdc36e"}
image.src = {mainSampleImg};# the value of image.src is http://localhost:8080/proxy/[object%20Object]
}
}
...
Since img.src has value http://localhost:8080/proxy/[object%20Object], it becomes images not found, what is the right way to specify the images from images/my_img.jpg? (just for info, I am using webpack)
You assign an object to image.src instead of a string:
// not { mainSampleImg }
image.src = mainSampleImg;
if you put images in your public folder then you can just import like so:
<img src={'/path/under/public/route/filename.jpg} />
so if you have public folder with images directory and file is football.jpg you would do:
<img src={'/images/football.jpg'} />
no need to import images at the top of the file
Related
I am trying to create a marker with a custom icon. I created a new folder inside the component I am working with the images. I imported the image the image from the folder and tried using it. The problem is the marker is either not showing or I get an error.This is what my code looks like.
import hereIcon from './images/hereIcon.png';
const iconHere = <img src={hereIcon} />;
marker = new H.map.Marker(coordinate,
{
icon: new H.map.Icon(iconHere,
{ size: { w: 56, h: 56 } }),
});
My question is, how can I use the icon from a folder. I tested it with with an URL and it's working but I need it to work from a folder inside my project.
If you need to add local image, you can use DOM Marker like below code:
var kMarkerSearchResult = "file:///resources/images/SearchResult.png";
var markerHTML = '<div>' + '<img src="' + kMarkerSearchResult +'">' + '</div>';
var domIcon = new H.map.DomIcon(markerHTML);
var bearsMarker = new H.map.DomMarker({lat: 53.430, lng: -2.961 }, { icon: domIcon });
map.addObject(bearsMarker);
Don't forget to put "file: ///" at the beginning of the path.
For context, I was reviewing Dynamically import images from a directory using webpack
When trying to use the importAll(i) function,
It seems that my images object does not get populated and/or the images object is undefined.
Can anyone help as to where I am going wrong?
function importAll(i) {
let images = {};
i.keys().map((item, index) => {images[item.replace('./', '')] = i(item);
return images;
});
}
const images = importAll(require.context('../images', false, /\.png$/));
<img src={ images['chatLogo.png'] } alt="Chat Logo" width="300" height="250" />
My file directory:
I've got it in the components folder as I was trying to figure out if it was my filepath that was the issue.
Your importAll function doesn't return images, your map function does. You need to move a } up so the return statement is in the outer function.
Formatted for clarity, but otherwise unmodified:
function importAll(i) {
let images = {};
i.keys().map((item, index) => {
images[item.replace('./', '')] = i(item);
return images; // <-- this should be outside the map function
});
// return images; <-- should be here
}
Currently I am trying to fetch the github readme file and render it using ReactMarkdown. here is the screenshot of output/error.
there are some tag like
<p float="left"> <img src="https://github.com/username/project/blob/master/Screenshots/s1.png" width="300" hspace="40"/> </p>
So above tag does not render and gives CORB error.
My current code is
<ReactMarkdown
className="projectDetail__markdown"
escapeHtml={false}
transformImageUri={(uri) =>
uri.startsWith("https")
? uri
: `https://raw.githubusercontent.com/AlShevelev/WizardCamera/master/screenshots/5_2_small.webp`
}
source={markDown}
// astPlugins={[parseHtml]}
renderers={{ code: CodeBlock }}
</ReactMarkdown>
I have tried use plugin but no success.
Finally I founded the solution.
I saw CORB error in console I research about why this was happening and founded that in readme file url of images were not correct.
The readme url were https://github.com/username/project/blob/master/Screenshots/s1.png &&
required Url was: https://raw.githubusercontent.com/username/project/master/screenshots/s1.png
So the problem was that when we set the src for the image, we need to use a URL which points to an actual image and first url was not pointing to actual image.
this was the root cause and because of this images were not rendering.
So I write code to convert all the urls of img tags only of markdown response.
https://playcode.io/666242/ complete code.
// This function will find all the links in img tag.
function getImages(string) {
const imgRex = /<img.*?src="(.*?)"[^>]+>/g;
const images = [];
let img;
while ((img = imgRex.exec(string))) {
images.push(img[1]);
}
return images;
}
// This function convert the markdown text.
const convertImgInMarkdown = (markDown) => {
let mark = markDown;
let imageTags = getImages(mark);
let updatedImages = [];
imageTags.map((image) => {
let xx = image.split(".com");
let y = `https://raw.githubusercontent.com` + xx[1];
let z = y.replace("/blob", "");
updatedImages.push(z);
});
for (let i = 0; i < updatedImages.length; i++) {
mark = mark.replace(imageTags[i], updatedImages[i]);
}
return mark;
};
I am new to React and react hook I want to upload an image from anywhere but I want to know the width and height of a select image before storing it in the database. I want to store the original image metadata width and height. anyone can help me
One solution can be to use FileReader, something like this should work:
const image = new Image();
let fr = new FileReader();
fr.onload = function() {
if (fr !== null && typeof fr.result == "string") {
image.src = fr.result;
}
};
fr.readAsDataURL(inputFile);
image.onload = async function() {
const width = image.width;
};
You can take a look here: https://github.com/toncic/Image-Classification/blob/master/src/Components/ImageClassification.tsx#L45
Could you please tell me how to replace image source in react? .I am setting a src url to my img tag.
If image is not present on server I want to replace src url to this one http://punemirror.indiatimes.com/photo/55813567.cms
if image is present on server then it fine .if not then I need to change source url to "http://punemirror.indiatimes.com/photo/55813567.cms
"
here is my code
https://codesandbox.io/s/KOrGKp3B8
I try like that
imageExists(url, callback) {
var img = new Image();
img.onload = function () {
callback(true);
};
img.onerror = function () {
callback(false);
};
img.src = url;
}
renderList() {
const lis = this.items.map((item, key) => {
var src = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";
return (
<li key={key}>
<a><img src={src}/><span>{item.hl}</span></a>
</li>
)
})
return (
<ul>
{lis}
</ul>
)
}
render() {
return (
<div className="list">
{this.renderList()}
</div>
)
}
}
Check if your image exists, use this method and then in your component class :
componentWillMount() {
var url = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";
var src = this.imageExists(url) ? url : alt;
this.setState({ src });
}
// added from the mentioned post
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
render() {
var src = this.state.src;
...
}
You can use object for this.
<object data={src} type="image/png">
<img src="http://punemirror.indiatimes.com/photo/55813567.cms" />
</object>
On component render, you need to check server-side for all present files, and return an array of all file ids you got on the server.
When you get that array of existing files, let's call it allFileIds, you just need to do :
<li key={key}>
<a><img src={allFileIds.indexOf(item.id) !== -1 ? src : alt}/><span>{item.hl}</span></a>
</li>
This will check if the required id was found on the server (it checks if the item.id value exists in the array of file ids that your server returned), and if not, render the alt property instead of the src. I hope that was clear!
First put your image collection in state instead of field.
I assume each image in your images collection contains at least one field: url. You can check your images (this.items) for existence in componentDidMount/componentWillReceiveProps. Note that your imageExists method is async - therefore you cant use it during rendering. Based on the check you can set img.src to be either undefined/null or valid URL.
Then in render check image.url and if it is missing - use default one.