Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Blob to image inside Cell in React

The value can be accessed like: myObj.value and it is blob:http://localhost:3000/304dbb9b-6465-4dc8-8b2c-5a25fae7e452

Cell component:

export default class Cell extends React.PureComponent {
  render() {
    const { label, value } = this.props;
    return (
      <td>
        {label && (
          <div>
            <span className="cell-label">{label}</span>
            <br />
          </div>
        )}<span>{value}</span>                              
        )}
      </td>
    );
  }
}

if I do it like in the following example, it shows the string value and I want to show the actual image. Is this possible?

<tr>
    {myObj.map(item => (
                <Cell
                  key={myObj.indexOf(item)}
                  label={item.label}
                  value={item.value} //I guess something here must be changed
                />
              ))}
</tr>
like image 760
Leo Messi Avatar asked Oct 22 '25 07:10

Leo Messi


1 Answers

Try converting the blob to dataUrl:

URL.createObjectURL(blob)

Source: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

Then you can load it as an image:

<img src={URL.createObjectURL(dataUrl)} />

or in your code something like:

<tr>
    {myObj.map(item => (
        <Cell
            key={myObj.indexOf(item)}
            label={item.label}
            value={URL.createObjectURL(item.value)}
        />
    ))}
</tr>

I'm hoping you can translate that into what you need. You can either transform the blob inside the component that renders <Cell /> or inside Cell. It sounds appropriate to put it inside Cell, so no other component has to care about the implementation details of the blob to dataUrl logic.

If you put it inside Cell, then you will need to call it like this:

// URL.createObjectURL(this.props.blob)


export default class ImageCell extends React.PureComponent {
  render() {
    const { label, blob } = this.props;
    return (
      <td>
        {label && (
          <div>
            <span className="cell-label">{label}</span>
            <br />
          </div>
        )}
          <span>
            <img src={URL.createObjectURL(blob)}>
          </span>
        )}
      </td>
    );
  }
}

...

<tr>
    {myObj.map(item => (
        <ImageCell
            key={myObj.indexOf(item)}
            label={item.label}
            blob={item.value}
        />
    ))}
</tr>
like image 107
agm1984 Avatar answered Oct 23 '25 20:10

agm1984



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!