javascriptreactjscodesandbox

Image file is not shown in CodeSandBox


I made a code using React and the code is working well if I run the code in local.

I moved the same code to 'CodeSandBox'. But the image files in the directory don't be shown.
I also made the same code using JavaScipt and it's also working well in 'CodeSandBox'.

I'll upload my code and CodeSandBox link. Would you check why it can't load image files well?

Code

import styled from "styled-components";
import { useState } from "react";

export default function App() {
  const [valueX, setValueX] = useState(0);

  const mouseHandle = (e) => {
    setValueX(e.clientX);
  };

  return (
    <Wrap onMouseMove={mouseHandle} valueX={valueX}>
      <section>
        <div id="bg"></div>
        <h2>2.5D Parallax Effects</h2>
        <img src="img.png" className="girl" />
      </section>
    </Wrap>
  );
}

const Wrap = styled.div`
  margin: 0;
  padding: 0;
  font-family: "Poppins", sans-serif;

  section {
    position: relative;
    height: 100vh;
    overflow: hidden;
  }

  section #bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url(bg.jpg);
    background-size: ${(props) => `calc(100% + ${props.valueX / 2}px)`};
    background-position: center;
  }

  section .girl {
    position: absolute;
    top: 0;
    width: 400px;
    left: 50%;
    max-width: ${(props) => `calc(400px - ${props.valueX / 50}px)`};
  }

  section h2 {
    position: absolute;
    top: 50%;
    width: 100%;
    color: #fff;
    font-size: 8em;
    text-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    transform: ${(props) =>
      `translate(calc(10% - ${props.valueX * 2}px), -50%)`};
  }
`;

CodeSandBox

React https://codesandbox.io/s/2-5d-parallax-react-l9pdxp?file=/src/App.js

JavaScript https://codesandbox.io/s/2-5d-parallax-javascript-ix4f5q?file=/index.html


Solution

  • In the Codesandbox setup for React, the assets that needs to be referenced from the root path needs to be placed under the public directory.

    Try to move your bg.jpg and img.png into the public directory for it to work.


    Alternatively, the recommended solution is to move your assets (In this case bg.jpg and img.png) to be inside your src folder. After that, you can import that in your .tsx file and use it in your img tag and CSS, example below:

    import bg from './bg.jpg';
    import img from './img.png';
    
    const element = <img src={img} alt="girl" className="girl" />;
    
    const Wrap = styled.div`
      section #bg {
        background: url(${bg});
      }
    `;