Iterating a Buffer object via .map() and passing data to a component via props

Viewed 1150

In my application I get a Buffer object with data from a file. For each byte in that buffer I want to render Bar and pass the byte as prop. However, the map function seems to have a problem with the Buffer object as Bar is not getting rendered at all. When I change data to an normal array everything works.

What am I doing wrong here?

import React from 'react';

function Bar(props) {
    return (
        <>
            {console.log(props.data)}
        </>
    )
}

function foo() {
  // var data = [0,1,2,3,4,5]
  var data = new Buffer([0,1,2,3,4,5])
  
  return(
    <div>
       {data.map((a) => {
          console.log(a) //correct data here
          return <Bar data={a} />;
       })}
    </div>
  )
}
```
3 Answers

The reasons your code is not working is because map callback method on Buffer (Uint8Array) is supposed to return another Uint8 as a result but as you are not returning Uint8 value, it assumes default value, 0.

I wouldn't explain in much details, but you can run following snippet to understand inner working of map function on Uint8Array.

const uint8 = new Uint8Array([25, 36, 49]);
const mappedArray = uint8.map(i => 'a');

console.log(mappedArray);

You can fix this issue in your code by iterating through buffer beforehand and preparing an array of react elements you want to render like following:

function Bar(props) {
  return (
    <span>
      {props.value}
    </span>
  )
}

function Foo(props) {
  const data = new Buffer([0, 1, 2, 3, 4, 5]);
  const items = [];

  for (const [index, value] of data.entries()) {
    items.push(<Bar key={index} value={value} />);
  }
  return (
    <div>
      {items}
    </div>
  );
}

Does the Buffer class has a method map()? JavaScript arrays are objects of the Array class, which has Array.prototype.map method. The Buffer class is probably lacking such a method. You can either iterate over the Buffer manually or implement a similar method for the Buffer class.

new Buffer does not return an Array. It returns an Uint8Array. Even if Uint8Array actually has a .map function in it's prototype, it will not get rendered properly by React.

Just convert it into an Array.

const data = [...new Buffer([0,1,2,3,4,5])];

or

const data = Array.from(new Buffer([0,1,2,3,4,5]));

Note: mapping over an Uint8Array still returns an Uint8Array, that's why nothing gets rendered. React render does not accept Uint8Array.

Related