PeterFEDev
PeterFEDev

Reputation: 11

ReactJS 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;

Upvotes: 1

Views: 86

Answers (1)

FK82
FK82

Reputation: 5075

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:

  • I refactored the onChange handler of the city select into updateCity
  • updateCity also updates state.selectedHotel to the first hotel for the city
  • you should bind the value prop of the hotel and city selects to selectedCity and selectedHotel respectively to select the corresponding option

Code for 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 }));
}

Upvotes: 1

Related Questions