How to get file path in react js

In ReactJS, you can get the file path using the input element’s “files” property. Here is an example:

    
      import React, { useState } from 'react';

      function FileInput() {
        const [filePath, setFilePath] = useState('');

        const handleFileChange = (e) => {
          const path = URL.createObjectURL(e.target.files[0]);
          setFilePath(path);
        };

        return (
          <div>
            <input type="file" onChange={handleFileChange} />
            <p>File Path: {filePath}</p>
          </div>
        );
      }

      export default FileInput;
    
  

In the above example, we have a functional component called “FileInput” which renders an input element of type “file”. We have used the useState hook to store the file path in the “filePath” state variable.

When the user selects a file using the input element, the “onChange” event is triggered, and the “handleFileChange” function is called. Inside this function, we use the “URL.createObjectURL” method to get a temporary URL representing the selected file’s data.

We then update the “filePath” state variable with the obtained file path. The file path is then displayed below the input element using the {filePath} expression.

Remember to import the necessary React components and hooks in your application to use the code mentioned above.

Leave a comment