1

I'm attempting to build a Select dropdown and populate the input fields using a for loop.

import React, { Component } from 'react';

export default class Test extends Component {
  render() {
    let options = [];
    for (let i=2; i < 20.5; i += 0.5){
      options.push(<option value={i*60} key={i}>{i} hours</option>)
    }
    return (
      <select>
        {options}
      </select>
    )
  }
}

The {i} hours section causes an Uncaught TypeError: Cannot read property 'props' of undefined error message. Changing it to a fixed string prevents the error.

I'm sure I'm missing something basic but I have no idea why this isn't working.

11
  • Works for me, usually the 'props' of undefined issue is with a this binding - is there more code somewhere? Commented Mar 1, 2016 at 5:20
  • I thought it may have been some other code but I made this test component and render it directly to the page using the code below and it still occurs: ReactDOM.render(React.createElement(Test), document.querySelector('.react-container')); Commented Mar 1, 2016 at 5:25
  • A Jsfiddle would help :) Commented Mar 1, 2016 at 5:26
  • dont use React.createElement for es6 classes, just render the JSX ie ReactDom.render(<Test />, document.querySelector('.react-container')); createElement should only be used w/ components created with createClass Commented Mar 1, 2016 at 5:29
  • Thanks for the tip. I only used it for the purposes of this test to completely isolate this snippet from the rest of my code. Commented Mar 1, 2016 at 5:34

1 Answer 1

6

Try this:

import React, { Component } from 'react';

export default class Test extends Component {
  render() {
    const options = [];
    for (let i=2; i < 20.5; i += 0.5) options.push(i);
    return (
      <select>
        {options.map(option => (
          <option key={option} value={option*60}>
            {option} hours
          </option>
        ))}
      </select>
    )
  }
}

or (in 2021) as a function component:

export default const Test = () => {
  const options = [];
  for (let i=2;i<20.5;i+=0.5) options.push(i);
  return (
    <select>
      {options.map(option => (
        <option key={option} value={option*60}>
          {option} hours
        </option>
      ))}
    </select>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

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.