George Katsanos George Katsanos - 5 months ago 6
HTML Question

Render HTML from array items

I am attempting to render a list of HTML elements (links) stored in an array.

I am initially constructing the array as such:

const availableSizes = product.simples.filter((value) => {
return value.stockStatus === STATUS_AVAILABLE;
}).map((value, index) => {
return `${value.filterValue} `;
});


An example of the array contents is :

["35 ", "36 ", "36.5 ", "37.5 ", "38 ", "39 ", "39.5 ", "40 ", "41 ", "41.5 ", "42 ", "42.5 ", "43 ", "44 ", "44.5 ", "45 ", "46 ", "46.5 ", "48 ", "49 "]


I attempted to modify how each string is built as such:

const availableSizes = product.simples.filter((value) => {
return value.stockStatus === STATUS_AVAILABLE;
}).map((value, index) => {
return `<a href="#">${value.filterValue}</a>`;
});


but the HTML was escaped and printed directly in the output without it being parsed as HTML but as a common string.

Please note that not only I need to render the links but I also need to have onClick handlers that do specific actions (save a cookie for example), so the links need to be handled by React as well.

Answer

As you have JSX available you could do the following instead:

class MyComponent extends React.Component {
  render() {
    const availableSizes = product.simples
      .filter((value) => value.stockStatus === STATUS_AVAILABLE)
      .map((value, index) => <a key={index} href="#">${value.filterValue}</a>);

    return (
      <div>
        {availableSizes}
      </div>
    );
  }
}

Pay attention to the key={index} that I added. React needs this to optimise the rendering process. If you have a unique id for each product you could use that instead for a better optimisation. It's used in React's diffing algorithm. For example: <a key={value.id} href="#">${value.filterValue}</a>