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
we use
process.env.PUBLIC_URL
to get theURL
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:and
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.
You can access files in public folder directly in React.
For example:
If you want to export an array of files, for example:
And then import the files array, for example:
To append an image to your component using
d3
, you can used3.select
ord3.selectAll
to select the element where you want to add the image, and then useappend
orinsert
to create a new element.For example:
You can find more details and examples to
append
andselect
using d3.