reactjs - Trying to create a controlled switcher button -
i've picked code online (it's high in google results) : https://codepen.io/builtbyedgar/pen/jwovyq
but i've grown annoyed it's code.
i'm trying have duo of these buttons default state on , having both off not allowed. ui behavior i've chosen re-enable other if it's sibling being turned off :
ononeclick() { let { two, one, } = this.state; if (two) { 1 = !one; } else if (one) { 2 = !two; 1 = !two; } else { 1 = !one; } this.setstate({ one, two, }); this.props.callback({ one, two, }); } ontwoclick() { let { two, one, } = this.state; if (one) { 2 = !two; } else if (two) { 2 = !two; 1 = !one; } else { 2 = !two; } this.setstate({ one, two, }); this.props.callback({ one, two, }); }
and render:
<div> <div classname="switch-container"> <label> <input onchange={this.ononeclick} type="checkbox" classname="switch" value={this.state.one} checked={this.state.one} /> <div> <span><g classname="icon icon-toolbar grid-view" /></span> <span><g classname="icon icon-toolbar ticket-view" /></span> <div /> </div> </label> </div> 1 </div> <div> <div classname="switch-container"> <label> <input onchange={this.ontwoclick} type="checkbox" classname="switch" value={this.state.two} checked={this.state.two} /> <div> <span><g classname="icon icon-toolbar grid-view" /></span> <span><g classname="icon icon-toolbar ticket-view" /></span> <div /> </div> </label> </div> 2 </div>
simple enough right?
problem react hates switcher input of type "checkbox" :
and can see i've done best avoid happening think isn't in cards have input type , change it's checked state other human.
so i'm thinking maybe can solve issue reconstructing checkbox divs. (the label tag in violation of eslint)
answered jlaitio :
and here's added (top part of file props declaration , constructor) :
const proptypes = { value: react.proptypes.object, type: react.proptypes.string, callback: react.proptypes.func, one: react.proptypes.bool, two: react.proptypes.bool, }; const defaultprops = { callback: () => {}, onchange: () => { }, value: { type: '' }, one: true, two: true, }; class providerinfoscomponent extends component { constructor(props) { super(props); const initialvalue = props.value; this.state = { ...initialvalue, one: this.props.one, two: this.props.two, }; this.ononeclick = this.ononeclick.bind(this); this.ontwoclick = this.ontwoclick.bind(this); }
you error, if @ any point value
attribute not set, or set value undefined
, , subsequently existing react state value.
my best guess constructor not initialize one
, two
, hence value being undefined
start with. when have value, component transfers being uncontrolled (="component state independent of react") controlled(="component state tied directly react state").
Comments
Post a Comment