I have a React-Select Component which renders a drop-down Menu and when an item from the dropDown is selected a button get´s rendered.
import React, { Component } from 'react';
import Select from 'react-select';
class selectDemo extends Component {
state = {
selectedOption: '',
data: [
{Model: 'Option1'},
{Model: 'Option2'},
],
}
//Handler for Select Drop Down
handleChange = (selectedOption) => {
this.setState({selectedOption}, ()=>console.log(this.state.selectedOption.Model));
}
RenderButton = () => {
return <button type="button" className="btn btn-primary">{this.state.selectedOption.Model}</button>
}
render() {
console.log(this.state.selectedOption);
const { selectedOption } = this.state;
const value = selectedOption && selectedOption.Model;
return (
<div>
<div name="selectedOption" className="section">
<Select
className='form-control'
placeholder='Select Option'
name="selectedOption"
value={value}
onChange={this.handleChange}
labelKey='Model'
valueKey='Model'
optionClassName='dropdown-item'
options={this.state.data}
/>
</div>
<div className="section">
{this.state.selectedOption.Model && <this.RenderButton/>}
</div>
</div>
);
}
}
export default selectDemo;
However if I clear the value ,i.e. not choosing another one but clicking the x to remove my selection I get an
TypeError: Cannot read property 'Model' of null
Error at exactly Line 54 where I am actually checking wether the value is 'null' or 'undefined'. I tried with typeof
, if
and switch
statemements after reading:
- Is there a standard function to check for null, undefined, or blank variables in JavaScript?
- JavaScript checking for null vs. undefined and difference between == and ===
but this doesn´t work as well.