React props not working inside <img> tag, but works outside

Viewed 11

This is my index.js React App

import React from "react";
import ReactDOM from "react-dom";
import { faker } from '@faker-js/faker';

const App = () => {
    const avatarx = faker.image.avatar();
    return ( 
        <img alt="avatar" src='{avatarx}' />
    );
}

ReactDOM.render(<App />, document.querySelector('#root'));

It shows a warning that says 'avatarx' is assigned a value but never used.

If i use the prop {avatarx} outside of the <img> tag, then it shows the url of the image(so its working).

But it doesn't work inside the <img> tag?

2 Answers

Change this line to

<img alt="avatar" src='{avatarx}' />  // you're treating avatarx as a string 

to this line

<img alt="avatar" src={avatarx} /> // remove the single quotes from src attribute

Remove the quotes around the braces:

<img alt="avatar" src={avatarx} />

When using attributes in JSX elements, there are a couple options:

<Example
  truthyAttribute
  stringAttribute="foo"
  otherAttribute={[1, 2, 3]}
/>

The truthyAttribute without an explicit value will be set to true on the element.

The stringAttribute does not need braces and will be set to its string value on the element.

All other types of values (numbers, arrays, object and all variables) must be wrapped in braces. It is also valid to wrap string values in braces!

In your case, you did it the wrong way around so your src attribute was the literal string {avatarx} instead of the content of the variable. The warning you saw was fully justified.

Related