0

I have the following code:

import styled from "styled-components";

import avatar from './assets/images/2020-avatar.png'

function App() {
  return (
      <Container>
        <Avatar src={avatar} />
        <Medium src={require("./assets/images/medium_512.png")} />
      </Container>
    );
  }

const Container = styled.div`
  position: relative;
  display: flex;
`;
;

const Avatar = styled.img`
  top: 120px;
  width: 200px;
  height: 200px;
  position: absolute;
  left: 583px;
  object-fit: contain;
`;

const Medium = styled.img`
  top: 475px;
  left: 475px;
  width: 150px;
  height: 150px;
  position: absolute;
  object-fit: contain;
`;


export default App;

All of the references I've seen regarding the require() statement should work for the medium_512.png image, but it shows as a broken image. Only the imported avatar image works.

Wondering what I'm doing wrong here and why all the examples I've seen using require I have similar syntax, but obviously something is wrong.

mbspark
  • 534
  • 3
  • 18
  • Read this answer https://stackoverflow.com/questions/64910839/require-function-not-working-with-image-in-react/64911131#64911131 – kunquan Feb 10 '21 at 22:39
  • A couple of things, Require isn't an in-built function in js, it has to be added in or it automatically works when running the code with node. Because of this, webpack doesn't always require the file correctly. Secondly, imports and requires happen at the beginning so having it nested within code may be causing the issue. – Jon Baltz Feb 10 '21 at 22:41
  • @kunquan have right. but you can try with dynamic import. – Robert Feb 10 '21 at 22:41
  • I had tried placing the files in the public directory, but they were broken as well (even though no errors were shown on the console). In looking at the answer posted above, I adjusted my link. I had `../public/images/Avatar.png` and just needed to remove "public" to be `../images/Avatar.png` as "public" as a top level was already loaded. :( – mbspark Feb 10 '21 at 22:44

0 Answers0