DEV Community

Cover image for HOW TO PREVIEW AN UPLOADED IMAGE WITH REACT.JS
Candie
Candie

Posted on • Updated on

HOW TO PREVIEW AN UPLOADED IMAGE WITH REACT.JS

As a developer, if your file upload component is a customized one, or you want users of your platform to be able to preview their uploaded image, i am going to explain how you can achieve that in few steps.

REQUIREMENT:
create a react project using this command:
npx create-react-app image-upload-preview

  • STEP 1 Create a react component
import react from 'react'

export default function ImagePreview(){
return <div></div>
}
Enter fullscreen mode Exit fullscreen mode
  • STEP 2 Add a file input component
*import react from 'react'*

export default function ImagePreview(){
return <div>
   <input type='file' name='image' />
</div>
}
Enter fullscreen mode Exit fullscreen mode
  • STEP 3 install this library to preview your uploaded image

npm install mrcandie-react-preview

import react from 'react'
import Preview from 'mrcandie-react-preview'

export default function ImagePreview(){
return <div>
      <input type='file' name='image' />
      <Preview />
</div>
}
Enter fullscreen mode Exit fullscreen mode

STEP 4

Extract uploaded image file using react useState hook

import react, {useState} from 'react'

export default function ImagePreview(){
const [image, setImage] = useState('')
return <div>
      <input type='file' name='image' onChange={(e)=> 
            setImage(e.target.files[0]} />
            <Preview />
</div>
}
Enter fullscreen mode Exit fullscreen mode

STEP 5
Pass the uploaded image/file as a prop to the Preview component

import react, {useState} from 'react'

export default function ImagePreview(){
const [image, setImage] = useState('')
const [imageUrl, setImageUrl] = useState('')
return <div>
      <input type='file' name='image' onChange={(e)=> {
            setImage(e.target.files[0]} />
            }
       <Preview file={image} />
</div>
}
Enter fullscreen mode Exit fullscreen mode

FINAL STEP
Voila! Your uploaded image is previewed;

import react, {useState} from 'react'

export default function ImagePreview(){
const [image, setImage] = useState('')

return <div>
      <input type='file' name='image' onChange={(e)=> {
            setImage(e.target.files[0]} />
            }
      <Preview file={image} />
</div>
}
Enter fullscreen mode Exit fullscreen mode

read more about mrcandie-react-preview documentation here

Top comments (0)