It is easy when we have individual options like this:
<select name="phone_type" id="phone_type">
<option value="mobile" selected>Mobile</option>
<option value="home">Home</option>
<option value="office">Office</option>
</select>
But in my case I'm doing this using a loop:
phoneTypes = ['Mobile', 'Home', 'Office'];
...
<select onChange={(e) => this.handleChangePhonetype(e, index)}>
{this.phoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType} name="type">
{phoneType}
</option>);
})}
</select>
I searched the internet but couldn't get a proper answer for React. I want 'Mobile' to be selected already when the page loads. I don't know how to do this in React. Please pitch in.
Here is the stackblitz.
CodePudding user response:
You should simply use the type
of each phone object as the value to the select
element.
Here's the updated stackblitz.
const PhoneTypes = ['Mobile', 'Home', 'Office'];
class Questionnaire extends Component {
state = {
phones: [{ type: 'Mobile', number: '' }],
};
addContact() {
this.setState((prevState) => ({
phones: [...prevState.phones, { type: 'Mobile', number: '' }],
}));
}
handleChange({ target: { name, value } }, phoneIndex) {
this.setState((prevState) => ({
phones: prevState.phones.map((phone, index) =>
phoneIndex === index ? { ...phone, [name]: value } : phone
),
}));
}
handleRemove(phoneIndex) {
this.setState((prevState) => ({
phones: prevState.phones.filter((_, index) => phoneIndex !== index),
}));
}
handleSubmit(e) {
console.log(this.state, '$$$');
}
render() {
return (
<div>
<h1>The Form</h1>
<label>Contact</label>
{this.state.phones.map((phone, index) => {
return (
<div key={index}>
<input
onChange={(e) => this.handleChange(e, index)}
value={phone.number}
name="number"
/>
<select
name="type"
value={phone.type}
onChange={(e) => this.handleChange(e, index)}
>
{PhoneTypes.map((phoneType, index) => {
return (
<option key={index} value={phoneType}>
{phoneType}
</option>
);
})}
</select>
<button onClick={(e) => this.handleRemove(index)}>Remove </button>
</div>
);
})}
<hr />
<button onClick={(e) => this.addContact(e)}>Add contact</button>
<hr />
<button onClick={(e) => this.handleSubmit(e)}>Submit</button>
</div>
);
}
}
I also fixed some other issues like mutating the state, incorrect arg to remove function etc.