I'm using SelectField of material-ui for my react project. I have tried many ways from this answer Can't get the target attributes of material-ui select react component .
But they don't work.My target.id always equals "" How can I get the attributes (like id).
Here is my code:
constructor(props) {
super(props);
this.state = {
form: {
resident_city: ''
},
ret_code: '',
ret_msg: ''
};
this.handleList = this.handleList.bind(this);
}
handleList(event, index, value) {
event.persist()
const field = event.target.id;
const form = this.state.form;
form[field] = value;
console.log(event, value)
this.setState({
form
});
console.log(form);
}
<form>
<SelectField
style={style}
id="city"
value={this.state.form.resident_city}
onChange={this.handleList}
maxHeight={200}
>
{cities}
</SelectField>
</form>
I tried to use SelectField without form,and I still can't get the id attributes.It is really confusing me.
I read this issus Identify which [SelectField] [DropDownMenu] fired onChange and his question on stackoverflow Identify which [SelectField] [DropDownMenu] fired onChange
Although the answer is a way to solve this problem,but I want to know how can I get id attribute like Textfield name?
My question on stackoverflow Can't get attributes of material-ui SelectField in react
Any help would be great appreciate.
@TracyDa I have the same question, and it confuse me now
@TracyDa
The link you added helped me to fix the issue. I don't think there is another good solution to this.
I tried to get to the parent element by doing event.target.parentElement.parentElement but that didn't work either.
On the main component you define a prop name for select the form component let say your city component is called : cityForm
in your cityForm component
handleSelectChange(e, index, value) {
this.props.selectChange(e, index, value, this.props.cityName);
}
render() {
return (
<SelectField
style={style}
value={this.props.city}
onChange={this.handleSelectChange}
maxHeight={200}
>
{cities}
</SelectField>
);
}
}
In your main comp you will have let say (code is cutted some part omitted)
handleSelectChange(e, index, value, name){
this.setState({
[name] : value,
});
}
render(){
return (
<cityForm cityName = "city1" city={this.state.city1} selectChange={this.handleSelectChange}/>
);
}
}
Im building a dynamic form generator and it did the trick for me =) no need to pass an argument directly in the bind.
Most helpful comment
@TracyDa I have the same question, and it confuse me now