hello im trying to make a image upload and preview but i can only find react tutorials on how to do this using class components
import React from 'react';
const AddNew = () => {
const fileHandler = (event) => {
console.log(event.target.files[0])
}
const alt = (event) => {
return(event.target.files[0].name)
}
const preview = (event) => {
return (
URL.createObjectURL(event.target.files[0])
)
}
return (
<div className="addNew">
<img src={preview} alt={alt}/>
<input type="file" onChange={fileHandler} />
</div>
)
}
export default AddNew
how do i preview it using this syntax?
i get an error for invalid values for props 'src' and 'alt'
Multiple Images Upload Preview in ReactDefine fileObj array variable, we will insert image preview urls in this array using URL. createObjectURL() method for showing multiple images preview before uploading to the server.
To display an image from a local path in React:Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
You need to use state to let React know when to re-render. You can use useState hook to save your component state and file information, and when it changes, React knows it's the time to render.
const AddNew = ({}) => {
const [file, setFile] = React.useState(null)
const fileHandler = (e) => {
setFile(e.target.files[0])
}
return (
<div>
<img src={file? URL.createObjectURL(file) : null} alt={file? file.name : null}/>
<input type="file" onChange={fileHandler} />
</div>
)
}
ReactDOM.render(<AddNew />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With