Joshua Rajandiran
Joshua Rajandiran

Reputation: 2928

Why am I getting an uncaught type error when using map in React JS jsx?

I'm creating a component for selecting an input based on available options in my courses object.

I'm currently getting this error: Uncaught TypeError: Cannot read property 'map' of undefined

Here is my code:

const SelectInput = ({name, label, onChange, defaultOption, value, error, options}) => {
    return (
        <div className="form-group">
            <label htmlFor={name}>{label}</label>
            <div className="field">
                {/* Note, value is set here rather than on the option - docs*/}
                <select name={name} value={value} onChange={onChange} className="form-control">
                <option value="">{defaultOption}</option>
                {options.map((option) => {
                    return <option key={option.value} value={option.value}>{option.text}</option>;  
                })}
                </select>
                {error && <div className="alert alert-danger">{error}</div>}
            </div>
        </div>
    );
};

Anyone knows the reason?

Upvotes: 0

Views: 68

Answers (1)

Vitaly Kravtsov
Vitaly Kravtsov

Reputation: 970

You expect that options are an array but you provide undefined options prop, so there is no map method for undefined

Provide not undefined options or try this:

const SelectInput = ({name, label, onChange, defaultOption, value, error, options = []}) => {
  ...
}

Upvotes: 1

Related Questions