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

4
  • use an array? any todo example has an array rendering Commented Feb 1, 2020 at 19:31
  • Buy how do I add and update dynmaicly an img src tag , its not just data Commented Feb 1, 2020 at 19:56
  • You have an array of images but in your code there is only one image. Please edit your question to clarify this point. Commented Feb 1, 2020 at 19:59
  • updated, the data is live , i dont have a list of images before , I need to make a placeholder Commented Feb 1, 2020 at 21:27

1 Answer 1

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 )

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.