0

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.

2
  • 1
    Are you using jsx? If yes why not return <a key={index}>{value.filterValue}</a> ? Commented Jul 7, 2016 at 10:02
  • I'm pretty sure that doing it how Yury says will fix this Commented Jul 7, 2016 at 10:03

2 Answers 2

3

In .map you return String however you should return JSX

const availableSizes = product.simples.filter((value) => {
  return value.stockStatus === STATUS_AVAILABLE;
}).map((value, index) => {
  return <a key={ index } href="#">{ value.filterValue }</a>;
});
Sign up to request clarification or add additional context in comments.

Comments

1

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>

3 Comments

you're not returning something from map and there's a JS error thrown :/
The return is implicit when you have a single expression within an anonymous function.
indeed, in my code I used the { } notation so I guess it expected a return.

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.