[SOLVED] How to use Mozilla HTML objects in react JavaScript

Issue

This Content is from Stack Overflow. Question asked by user261130

const filereader=new FileReader()

filereader.onload(e)=>(e.target.file)}
const file= document.getElementById(“filename”).files[0];
return (

)

i found this from mozilla but i think this not working with react,i am trying to create upload files by fetch or by post
so biggest question is that was html so what a best and effective source for react for search these types of methods or do i need to go with change mozilla html to react but by that console not showing errors its like blank screen, for effective learning every line of code should be understood



Solution

A basic e.g to upload file, you can check more here in
Docs

// Get a hook function
const {
  useState
} = React;

const App = () => {
  const [src, setSrc] = useState(null);
  const [file, setFile] = useState(null);

  const submitFile = () => {
    if (!file) return;

    const formData = new FormData();
    formData.append('avatar', file);

    fetch('https://api.imgur.com/3/image', {  // replace your API here
        method: 'POST', 
        body: formData
      })
      .then((response) => response.json())
      .then((result) => {
        console.log('Success:', result);
      })
      .catch((error) => {
        console.error('Error:', error);
      });
  };

  return ( <
    div >
    <
    input onChange = {
      (e) => setFile(e.target.files[0])
    }
    type = "file" / > < br / >
    <
    button onClick = {
      submitFile
    } > Upload File < /button> <
    /div>
  );
};

// Render it
ReactDOM.createRoot(
  document.getElementById("root")
).render( <
  App / >
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>


This Question was asked in StackOverflow by user261130 and Answered by KcH It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?