I have the following component (radioOther.jsx
):
'use strict';
//module.exports = <-- omitted in update
class RadioOther extends React.Component {
// omitted in update
// getInitialState() {
// propTypes: {
// name: React.PropTypes.string.isRequired
// }
// return {
// otherChecked: false
// }
// }
componentDidUpdate(prevProps, prevState) {
var otherRadBtn = this.refs.otherRadBtn.getDOMNode();
if (prevState.otherChecked !== otherRadBtn.checked) {
console.log('Other radio btn clicked.')
this.setState({
otherChecked: otherRadBtn.checked,
});
}
}
onRadChange(e) {
var input = e.target;
this.setState({
otherChecked: input.checked
});
}
render() {
return (
<div>
<p className="form-group radio">
<label>
<input type="radio"
ref="otherRadBtn"
onChange={this.onRadChange}
name={this.props.name}
value="other"/>
Other
</label>
{this.state.otherChecked ?
(<label className="form-inline">
Please Specify:
<input
placeholder="Please Specify"
type="text"
name="referrer_other"
/>
</label>)
:
('')
}
</p>
</div>
)
}
};
Prior to using ECMAScript6 all was well, now I am getting 1 error, 1 warning and I have a followup question:
Error: Uncaught TypeError: Cannot read property 'otherChecked' of null
Warning: getInitialState was defined on RadioOther, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
Can anyone see where the error lies, I know it is due to the conditional statement in the DOM but apparently I am not declaring its initial value correctly?
Should I make getInitialState static
Where is the appropriate place to declare my proptypes if getInitialState is not correct?
UPDATE:
RadioOther.propTypes = {
name: React.PropTypes.string,
other: React.PropTypes.bool,
options: React.PropTypes.array }
module.exports = RadioOther;
@ssorallen, this code :
constructor(props) {
this.state = {
otherChecked: false,
};
}
produces "Uncaught ReferenceError: this is not defined"
, and while below corrects that
constructor(props) {
super(props);
this.state = {
otherChecked: false,
};
}
but now, clicking the other button now produces error:
Uncaught TypeError: Cannot read property 'props' of undefined
getInitialState
is not used in ES6 classes. Instead assignthis.state
in the constructor.propTypes
should be a static class variable or assigned to the class, it should not be assigned to component instances.See more in the React's documentation about ES6 Classes: Converting a Function to a Class