Open In App

How to use files in public folder in ReactJS ?

Last Updated : 13 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In React the files store public folder contains static files such as index.html, javascript library files, images, and other assets, etc. which you don’t want to be processed by Webpack. Files in this folder are copied and pasted as they are directly into the build folder. Files inside the `public` folder can only be referenced from the HTML.

Approach to use files in public folder

To access and use files in the public folder in React we can use .env (environment) to store the url of the required file. Then this URL can be used in components/JS files present in the src folder. This grants access to the use of files in the public folder as needed.

Steps to create the applcation

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure

The project structure will look like the following after creating the assets folder with gfg.png file sample. Also, we have kept the gfgPublic.png file in the public folder.

Simple react app folder structure

Example: Here the link to file present in public folder is added to the .env and that is used in the Intro.js to access the required images as shown.

Python




# .env file
 
PUBLIC_URL = "./public/"


Javascript




// App.js  file
 
import Intro from './components/Intro';
import './App.css';
 
function App() {
  return (
    <div className="App">
      <Intro />
    </div>
  );
}
 
export default App;


Javascript




// Intro.js file
 
import gfgLogo from "../assets/gfg.png";
 
const Intro = () => {
    return (
        <div className="App">
            Image at src/assets/gfg.png : <br />
            <img src={gfgLogo} />
            <br />
            Image at public/gfgPublic.png: <br />
            <img
                src={
                    process.env.PUBLIC_URL + "/logo512.png"
                }
            />
            <br />
        </div>
    );
};
 
export default Intro;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Console window shows the exrenal import of the png.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads