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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With