简体   繁体   中英

Reactjs img tag not rendering the string in src:?

I am trying to render an image in reactjs. I am processing a URL and storing it in a global var URL. I want to use the populated URL in img tag src:

I have tried doing the following but didn`t work

<img
        src={url}

        style={{
          marginTop: '1px',
          marginLeft: '1px',
          marginBottom: '1px',
        }}
        height="500"
        alt=""
      />

my element inspection shows following for this above :

<img src height="500" alt="" style="margin-top: 1px; margin-left: 1px; margin-bottom: 1px;">
var url = '';
export default function ImageGallery() {

  const classes = useStyles()
  getList()
  return (
    <div>
    <Paper className={classes.root}>
      <img
        src={{url}}

        style={{
          marginTop: '1px',
          marginLeft: '1px',
          marginBottom: '1px',
        }}
        height="500"
        alt=""
      />
            <Link to={'/imageGalleryGrid'} style={{ textDecoration: 'none' }}>
              <Button variant="contained" className={classes.button}  style={{
                                                                               marginTop: '1px',
                                                                               marginLeft: '550px',
                                                                               marginBottom: '70px',
                                                                             }}>
                Checkout Gallery
              </Button>
            </Link>
      </Paper>



    </div>
  )
}

The image is not displayed: I am seeing URL in my console getting printed. Also, I am able to go to the URL and see the image.

It should be

<img
  src={url}
  // ...
/>;

where url must be a string .

If you add another pair of curly braces it turns into an object.

The double curly brace syntax is only used when you want to define an object inline, like for example when you're defining inline styles style={{color: 'red'}}

If you want to hardcode the url to test it, you can do it this way:

<img
  src="https://feelingfoodish.com/wp-content/uploads/2012/08/New-York-Style-pizza.jpg"
  // ...
/>;

About syntax and data type

The correct syntax is the one you are using in your second example (a single pair of curly braces):

<img src={url} ...`

Adding a second pair of curly braces means using the Object Literal Property Value Shorthand that is available from ES6/ECMA Script 2015. wich would be the same as writing

<img src={{url:url}} ...

So even if your url contains an empty string, the src attribute expects a string, converting evething else using it's toString() method. That is why you are seeing [Object object] when inspecting it.

About react life cycle, "global variables" and state

In case you are always storing the empty string in your var when your file gets initialized and are updating it later, react has no way of knowing that that variable has been updated, because this is state outside of the react life cycle.

If you are able to get to the correct URL with a normal function call (nothing asynchronous like fetching data from a server, etc) you can return the URL from that function and call it inside of you component('s render method) and use it directly (instead of using some "global variable"):

function Image() {
  var url = getImageUrl();
  return <img src={url}/>;
}

If you are not that lucky and need an async call to get your URL you need to introduce either local state (eg by using react hooks ) or some other method of storing the information and passing it as a prop to your component.

By the way: it very much depends on your (build or run time) environment whether a top level var declaration is a global variable. Since it is not exported it could also be a variable local to that module/file which can not be modified from other modules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM