javascript - Creating dependant fields in Reactjs? -
this render
<select> <option>1</option> <option>2</option> </select>
on selecting of options dropdown.i must render another dropdown list next it.
<select> <option>1</option> <option>2</option> </select> <select> <option>1.1</option> <option>1.2</option> </select>
then on selecting options second dropdown list.i must render input field of type text next it.
how implement in react?
var react = require('react'); var reactdom = require('react-dom'); var view = react.createclass({ getinitialstate: function() { return { value: '------' } }, handlechange: function(event){ this.setstate({value: event.target.value}); this.getfields(event.target.value); }, handleclick : function(){ }, render : function(){ return (<div> <p> <i classname="plussymbol fa fa-minus-circle"></i> <select onchange={this.handlechange} value={this.state.value} classname="js-example-basic-single"> <option value="">------</option> <option value="1">1</option> <option value="2">2</option> </select> </p> <p> <i onclick={this.handleclick} classname="plussymbol fa fa-plus-circle"></i> <span>add new condition</span> </p> </div>); }}); module.exports = view;
so view should [dropdown][dropdown][text field]
the following example should point in right direction...
var hello = react.createclass({ getdefaultprops: function () { return { fieldmap: { "1": [ { value: "1.1", label: "1.1" }, { value: "1.2", label: "1.2" } ], "2": [ { value: "2.1", label: "2.1" }, { value: "2.2", label: "2.2" } ] } } }, getinitialstate: function() { return { firstvalue: '', secondvalue: '', thirdvalue: '' } }, getoptions: function (key) { if (!this.props.fieldmap[key]) { return null; } return this.props.fieldmap[key].map(function (el, i) { return <option key={i} value={el.value}>{el.label}</option> }); }, handlefirstlevelchange: function (event) { this.setstate({ firstvalue: event.target.value, secondvalue: '', thirdvalue: '' }); }, handlesecondlevelchange: function (event) { this.setstate({ secondvalue: event.target.value, thirdvalue: '' }); }, handlethirdlevelchange: function (event) { this.setstate({ thirdvalue: event.target.value }); }, getsecondlevelfield: function () { if (!this.state.firstvalue) { return null; } return ( <select onchange={this.handlesecondlevelchange} value={this.state.secondvalue}> <option value="">---</option> {this.getoptions(this.state.firstvalue)} </select> ) }, getthirdlevelfield: function () { if (!this.state.secondvalue) { return null; } return ( <input type="text" onchange={this.handlethirdlevelchange} value={this.state.thirdvalue} /> ) }, render: function() { return ( <div> <select onchange={this.handlefirstlevelchange} value={this.state.firstvalue}> <option value="">---</option> <option value="1">1</option> <option value="2">2</option> </select> {this.getsecondlevelfield()} {this.getthirdlevelfield()} </div> ); } });
see live on https://jsfiddle.net/27u9lw4t/1/
Comments
Post a Comment