0

I am creating a web application with react. Currently I am trying to create cards that contain header text and an image.

My current problem is that when I import the image and try to use it like this:

import iwatch from './images/iwatch.jpg';
...
<img src = {iwatch} />

the image seems to appear but is displayed as 0x0. I am able to use css' background-image to get around this but creating css classes for each card is not the route I would like to take.

I read every post with the same issue as mine and attempted all solutions listed but nothing ever seemed to work.

Problem component:


const CategorySelectionContainer = () => {

  const categories = [
    {
      name: "Cell Phone",
    },
    {
      name: "Tablet",
    },
    {
      name: "Smart Watch",
    }
  ];
  return (
    <div>
      <div class = 'container'>
        <h2 class = 'center-text'>
          <strong>
            Select a device to get started.
          </strong>
        </h2>
        <div class = 'justify'>
        {categories.map((cat) =>
          <div key = {cat.name} class = 'card card-2 center-text card-container'>
            <div class = 'image'>
              <h4>{cat.name}</h4>
              <img style={{width:'auto',height:'auto'}} class = 'img' url = '/images/iwatch.jpg'/ >
            </div>
          </div>
        )}
        </div>
      </div>
    </div>
  );
};

export default CategorySelectionContainer

currently the image is in the public folder which is why i just reference the image without any curly braces.

I tried:

  1. Importing the image relative to the js file (as seen above)
  2. Moving the image to the public folder to reference it that way

I have a feeling it is something css related but I just have no idea what could be wrong. edit: I am able to use the in the app component and it displays correctly. Still not sure why.

1 Answer 1

1

In the code you have pasted in, you have used url to give the image tag a source link, please use src.

Another thing, use className instead of class.

<img style={{width:'auto',height:'auto'}} className='img' src='/images/iwatch.jpg'/ >

To get this work, the '/images/iwatch.jpg' needs to be in the right place, otherwise you can use the imported one like

<img style={{width:'auto',height:'auto'}} className='img' src={iwatch} / >
Sign up to request clarification or add additional context in comments.

2 Comments

and thats why I shouldnt be programming at 1 in the morning. Thanks! what difference does className bring?
React js reserves the keyword class, you need to use className, eventually react will turn into class anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.