reactjs - js - setState when select is rendered

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


reactjs - js - setState when select is rendered



I am new in react js. I am writing a class where I have two html 'selects'. First one set City and second one city. When I click button I should get info what has been selected by user. I keep/update state of City, but I have no idea how to set state of hotel when City has been changed. Do I need another separate component?


class CalendarForm extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedCity: "Warsaw",
selectedHotel: "Hilton"
};
}

showResult() {
const data = {
dzień: this.props.selectedDay,
miasto: this.state.selectedCity,
hotel: this.state.selectedHotel
};
console.log(data);
}

render() {
const { selectedCity } = this.state;
const CalendarForm = this.props.calendarForm;
const selectedDay = this.props.selectedDay;

const getHotels = () => {
const filterSelectedCity = CalendarForm.filter(
({ city }) => city === selectedCity
)[0];
return (
<div>
<select
onChange={e => this.setState({ selectedHotel: e.target.value })}
>
{filterSelectedCity.hotels.map((hotel, index) => (
<option key={index} value={hotel}>
{hotel}
</option>
))}
</select>
</div>
);
};

return (
<div>
<select onChange={e => this.setState({ selectedCity: e.target.value })}>
{CalendarForm.map(({ city, index }) => (
<option key={index} value={city}>
{city}
</option>
))}
</select>
{getHotels()}

<button onClick={this.showResult.bind(this)} type="button">
click
</button>
</div>
);
}
}

export default CalendarForm;





Welcome to StackOverflow Piotr! I have a hard time understanding exactly what you are having issues with. Do you want to reset the hotel when the city changes?
– Tholle
2 hours ago





or do you want to populate hotels after selecting city?
– devserkan
1 hour ago




1 Answer
1



Your code already works with a few subtle changes: here's a stackblitz which shows that the hotel select is being updated after the city changes.



Couple of things to note:


onChange


updateCity


updateCity


state.selectedHotel


value


select


selectedCity


selectedHotel


option



Code for updateCity:


updateCity


updateCity(event) {
const selectedCity = event.target.value;
const selectedHotel = this.props.calendarForm.find(({ city }) => city === selectedCity)
.hotels[0];

this.setState((oldState) => ({...oldState, selectedCity, selectedHotel }));
}





Please don't depend on code in external resources only. Can you edit your answer to include the relevant parts of your code?
– Patrick Hund
7 mins ago





@PatrickHund sure!
– FK82
3 mins ago






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.