Home > Blockchain >  Trying to use var as img src in JSX
Trying to use var as img src in JSX

Time:03-07

I'm working on a react project and I have a situation where I need the src attribute for an img tag to be a variable. The relevant parts of the code look something like this:

import React, { useState, useEffect } from 'react';

// topics is already defined and is a js object

const allTopics = topics.map(topic => {
        url = topic['image_url'];
        return (
            <Grid item key={ topic['topic_id'] } item xs={4}>
                <div class='img-wrapper'>
                    <img id='topicpreview' src={url} alt="loading" />
                    <h1>{topic['topic_name']}</h1>
                </div>
            </Grid>
        );
    });

return (
<div style={{ padding: '0', margin: '0', border: '1px solid black', width: '100%', height: '60%', overflow: 'hidden', display: 'inline-block' }} text-align='center'>
                <Grid container>
                    {allTopics}
                </Grid>
            </div>
    );

The image path exists and points to a valid file and I've console logged the url to make sure it's the same path. However, it doesn't find the image and ends up printing the "Loading" alternate text instead. I'm not sure what's going wrong, so any help would be appreciated!

CodePudding user response:

I think I understood your problem.

We cannot use a local path in img, because it will be referring to your local directory (not your website's domain)

To fix it, you need to call like below code snippet if you're using Webpack

const image = require(url); //or const image = require(url).default;

<img src={image} />

You also can try to find your local image with this URL localhost:3000/static/images/piano2.jpeg (your port may be different)

  • Related