How can I preview image using FileBase64?

Viewed 13

How can I preview the image that is store inside the useState using the Filebase64 before uploading it to the backend?, I tried to grab the url and then render it but it doesn't work.

I tried to use createObjectURL, but I think im using it wrong,

import { useState } from 'react'
import FileBase from 'react-file-base64'


const NewProduct = ({ inputs, title, products }) => {
  const [productData, setProductData] = useState({
    productName: '',
    productStock: '',
    productImage: '',
  })

  return (
          <div className="left">
            <img
             src={
            productData.productImage
              ? URL.createObjectURL(productData.productImage)
              : 'https://icon-library.com/images/no-image-icon/no-image-icon-0.jpg'
          }
              alt=""
            />
          <div className="right">
            <form>
              <div className="formInput">
                <label htmlFor="file">Image:</label>
                <FileBase
                  type="file"
                  multilple={false}
                  onDone={({ base64 }) =>
                    setProductData({ ...productData, productImage: base64 })
                  }
                />
              </div>

              <div className="formInput">
                <label>Product Stock</label>
                <input
                  type="number"
                  onChange={(e) =>
                    setProductData({
                      ...productData,
                      productStock: e.target.value,
                    })
                  }
                />
                <button onClick={handleClick}>Send</button>
              </div>
            </form>
          </div>
        
    </div>
  )
}

export default NewProduct

enter image description here

0 Answers
Related