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>
}
- STEP 2 Add a file input component
*import react from 'react'*
export default function ImagePreview(){
return <div>
<input type='file' name='image' />
</div>
}
- 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>
}
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>
}
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>
}
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>
}
read more about mrcandie-react-preview documentation here
Top comments (0)