Reputation: 36179
I have a Checkbox component which is simple checkbox under the hood however styled to my needs, as it has custom 'fake element' which acts as original one.
Checkbox
import React, {Component} from 'react';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import '../../../stylesheets/common/forms/Checkbox.scss';
export default class extends Component {
constructor(props) {
super(props);
this.state = {checked: props.checked};
}
toggle() {
const checked = !this.state.checked;
this.setState({checked});
}
/**
* custom prop indicates that we want create custom element to toggle checkbox ie. ImageCheckbox
*
*/
render() {
const {id, className, children, name, custom = false} = this.props;
const toggle = this.toggle.bind(this);
return (
<FormGroup className={`Checkbox ${className}`}>
<input id={id}
name={name}
type="checkbox"
checked={this.state.checked}
onChange={toggle}/>
{!custom && <div className="fake-checkbox" onClick={toggle}/>}
<label htmlFor={id}>{ children }</label>
</FormGroup>
)
}
}
As comment says it in code component allows to create a custom 'fake' element inside label to act as toggle for checkbox.
ImageCheckbox:
import React from 'react';
import Checkbox from '../../common/forms/Checkbox';
import '../../../stylesheets/common/forms/ImageCheckbox.scss';
export default props => (
<Checkbox className="ImageCheckbox" {...props} custom={true}>
<div className="image"
style={{backgroundImage: 'url(' + props.href + ')'}}>
<p>{ props.children }</p>
</div>
</Checkbox>
);
It works how I want but when i click ImageCheckbox I get warning in browser:
warning.js:36 Warning: _class is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://facebook.github.io/react/docs/forms.html#controlled-components
Im not sure what I do wrong and should I be concerned about it.
Upvotes: 0
Views: 850
Reputation: 36179
I found answer in Adam's reply React - changing an uncontrolled input.
I've change undefined
to false
in constructor when prop isn't passed:
constructor(props) {
super(props);
const {checked = false} = props;
this.state = {checked};
}
Upvotes: 0