javascript - How to apply an id attribute to a child element of a ReactJS component? -
so have dropdown component:
import react 'react'; import { proptypes } 'prop-types'; export default class dropdown extends react.component { constructor(props) { super(props); this.state = { value: this.props.selecteddropdownvalue, }; this.handlechange = this.handlechange.bind(this); } handlechange(e) { this.setstate({ value: e.target.value, }); this.props.onchange(e.target.value); } render() { let disabled = false; let dropdownoptions = null; const { options } = this.props; // disable dropdown disabled attribute added if (options) { dropdownoptions = this.props.options.map((option) => <option value={option.key} key={option.key} >{option.display}</option>, ); } else { // setting default options const defaultoptions = [ { key: '', display: 'please configure defaultoptions' }, ]; disabled = true; dropdownoptions = defaultoptions.map((option) => <option value={option.key} key={option.key} >{option.display}</option>, ); } return ( <select value={this.state.value} onchange={this.handlechange} disabled={disabled} > { dropdownoptions } </select> ); } } dropdown.proptypes = { options: proptypes.arrayof(proptypes.object), onchange: proptypes.func, selecteddropdownvalue: proptypes.string, }; dropdown.defaultprops = { options: undefined, onchange: this.handlechange, selecteddropdownvalue: '', };
and here how i'm rendering dropdown in view:
import react 'react'; import { proptypes } 'prop-types'; import dropdown 'components/dropdown'; class anish extends react.component { render() { return ( <div> <div> value selected: {this.props.selecteddropdownvalue} </div> <label htmlfor={'dropdownid1'}>sort by: </label> <dropdown id="dropdownid1" options={[ { key: '', display: 'please select value' }, { key: 'nj', display: 'new jersey' }, { key: 'ny', display: 'new york' }, ]} onchange={this.props.onsetdropdownvalue} /> </div> ); } } anish.proptypes = { selecteddropdownvalue: proptypes.string, onsetdropdownvalue: proptypes.func.isrequired, }; anish.defaultprops = { selecteddropdownvalue: '', }; export default anish;
here how dropdown , label rendered in browser:
so how can apply id that's on <dropdown />
<select>
inside of it?
any appreciated.
props
contain id dropdown
component, since you're within react component use this.props
.
return ( <select id={this.props.id} value={this.state.value} onchange={this.handlechange} disabled={disabled} > {dropdownoptions} </select> )
Comments
Post a Comment