skip to Main Content

I am just getting started on my first React app and initialized a template with create-react-app. I want to make a simple data visualization app. I put the data files that will be visualized into the public/ folder but can’t figure out how to access them from the application’s javascript code.

I try using process.env.PUBLIC_URL, but it’s empty. The app’s code (App.js) is only

import './App.css';

function App()

  console.log(process.env.PUBLIC_URL);

  return (
    <div className="App">
      <pre>app</pre>
    </div>
  );
}

export default App;

and the console prints nothing.

What am I doing wrong?

2

Answers


  1. we use process.env.PUBLIC_URL to get the URL to the public folder, it is empty because React now by default allows you to point directly to the public folder. For example, if you have an image folder under the public folder you can directly get the image URL string this way:

    <img src="/images/house.jpg" />
    

    and

    <img src={process.env.PUBLIC_URL + "/images/house.jpg"} />
    

    is equivalent because process.env.PUBLIC_URL is "".

    From your comment, it seems like your data stored are arrays so in this case you don’t need them in the public folder, you can leave them there, but you have to export them so you can import them from your App component.

    Login or Signup to reply.
  2. You can access files in public folder directly in React.

    For example:

    <img src='/images/1.jpg' />
    

    If you want to export an array of files, for example:

    export const files = [
        "/images/1.jpg",
        "/images/2.jpg",
        "/images/3.jpg",
    ];
    

    And then import the files array, for example:

    import { files } from "./files"
    

    To append an image to your component using d3, you can use d3.select or d3.selectAll to select the element where you want to add the image, and then use append or insert to create a new element.

    For example:

    const images_component = d3.select("#images-component")
    
    files.forEach(image => {
      images_component.append("img").attr("src", image);
    })
    

    You can find more details and examples to append and select using d3.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search