Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preview image upload with React Functions

Tags:

reactjs

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'

like image 214
jjlmc Avatar asked Apr 15 '20 04:04

jjlmc


People also ask

How do I preview multiple images before uploading in React?

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.

How do I display an image in a React file?

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" /> .


1 Answers

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"/>
like image 172
lhoro Avatar answered Sep 17 '22 14:09

lhoro