1

Admittedly learning react & jsx, but can't for the life of me figure out why this does not render:

function generateItem(item){
  return `<li><a href=${item.url}>${item.text}</a></li>`;
}

function MyList ({items}){
  return (
      <div className="list">
        <ul>
          {items.forEach(item => {
            generateItem(item);
          })}
        </ul>
      </div>
  );
};

All it outputs (when included in my app) is an empty list:

<div class="list"><ul></ul></div>

I'm sure it's something basic and fundamental. But there I am.

https://codesandbox.io/s/relaxed-stallman-81ety

1
  • 1
    1. Use map instead of forEach. 2. I would recommend to return jsx instead of a string and use the generateItem function as a functional component instead of a function that returns something. Commented May 22, 2019 at 23:14

1 Answer 1

4

items.forEach does not return anything... the things inside curly brackets in jsx will end up transpiled to an argument in a call to React.createElement, so they need to be an expression and return a value. (check here the transpiled version)

Try items.map(item => generateItem(item)) or simply items.map(generateItem) instead.

here's your code edited (I also changed generateItem to return jsx instead of a string)

https://codesandbox.io/s/frosty-sutherland-fp7kh

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

3 Comments

Hmm... so the whole "use can use regular javascript inside curly brackets" thing comes with some caveats. This helps.
@Trees4theForest your code works perfectly fine within curly brackets, it just doesn't return anything to render.
Here's an example that makes .forEach work by returning something from the expression. I would reject this in a code review, because .map is the most idiomatic way to do this, so just to illustrate the point: codesandbox.io/s/quizzical-haze-4mr8q

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.