Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React .- reduce() within JSX not rendering

Tags:

I have following code within render method:

return (<select>
{[...Array(24).keys()].reduce((acc, item) => `${acc} <option value="${item}">${item}<option>`, '')}
</select>);

acc variable contains all options, and reduce() function has implicit return but no options are displayed. What is explanation behind this?

I was able to make this work with .map(), I'm just curious what is the problem with the reduce function in the above example.

<select>
{[...Array(24).keys()].map(hour => {
return <option value={hour} key={hour}>{hour}</option>
})
}
</select>

Thanks

like image 291
Tom Avatar asked Sep 17 '18 09:09

Tom


1 Answers

If you look at the output in the inspector, you will see that you have a <select> which contains a text node. This is because you are building a string in your reducer. React renders strings as text, regardless of their content.

If you wanted to use reduce, then one option would be to do something like this:

ReactDOM.render(<select>
{[...Array(24).keys()].reduce((acc, item, index) => [
  ...acc, 
  <option key={index} value={item}>{item}</option>
], [])}
</select>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

This works because <option> creates an HTML element, not a string. The reducer returns an array of elements which can be rendered as HTML by React.

like image 142
Tom Fenech Avatar answered Sep 28 '22 18:09

Tom Fenech