0

I have a socket connection that updates a binary data.

By click I would like to update an image src , the images are created blank with empty src and with id , but I did not found how do I doing something like :

$('imageId').src = 'new src' like in Jquery

I have array of images so I cant define per each image this.ref or something

my socket code: // here I want to update the specific image

   divSocket.on('data', (data) => {
        var bytes = new Uint8Array(data);            
        this.setState({
            imageSrc : someBufferFunction(bytes)
        })
    });

my render code

   { this.props.list.map((item,i) =>(
     <div className="img">
        <img  id={`cam${i}`} src={`data:image/jpeg;base64,${this.state.imageSrc}`} />
     </div>
    ))}

the problem is that this.state.ImageSrc will update all images and will show socket data (video) in all the images

I can create an image with specific id in loop but how do I update specific image via props/state

Tuz
  • 1,810
  • 5
  • 29
  • 58

1 Answers1

2

You're using an array to display images ... from props ... this.props.list

This list should contain data for each image ... but item argument isn't used in .map rendering.

I need to make a placeholder

Assuming that props.list doesn't contain any data ... used as loop counter ... renders placeholders only ... you need:

  • an array of src in local state (this.state.sources = [];)
  • you should render images using key prop:
{ this.props.list.map((item,i) => (
    <div className="img" key={`cam${i}`} >
      <img  id={`cam${i}`} src={this.state.sources[i]} />
    </div>
))}
  • you can use placeholder image for empty 'cells'
<img  id={`cam${i}`} src={this.state.sources[i] ? this.state.sources[i] : "url_somePlaceholder.jpg"} />

New image from socket needs to update an array element using index - not common one for all images in this.state.sources - see React: how to update state.item[1] in state using setState? for inspirations.

If assumed earlier props.list contains image sources at start - copy values into state (in componentDidMount, componentDidUpdate or static getDerivedStateFromProps )

xadm
  • 8,219
  • 3
  • 14
  • 25