vendredi 26 août 2016

Controlling Checkboxes in React Js

I have a question in regards to how I should set up nested checkboxes.

I currently have nested data called areas that looks like this:

    [{
        "id": 1,
        "name": "Europe",
        "Countries": [{
            "id": 1,
            "name": "Iceland",
            "Cities": [{
                "id": 1,
                "name": "Selfoss"
            }]
        }, {
            "id": 2,
            "name": "Switzerland",
            "Cities": [{
                "id": 2,
                "name": "Geneva"
            }]
        }]
    }, {
        "id": 2,
        "name": "Asia",
        "Countries": [{
            "id": 3,
            "name": "Japan",
            "cities": [{
                "id": 3,
                "name": "Yokohama"
            }]
        }]
    }]

I need to generate them into nested checkboxes, which I have done successfully:

  const renderCities = Cities => {
    return (
      <div className="city-bar">
        <label>
          <input
              onChange={onChange}
              type="checkbox"/>
        {Cities.name}
        </label>
      </div>
    );
  };

  const showArea = Country => {
    return (
      <div className="country-bar"> 
        <label>
            <input
              onChange={onChange}
              type="checkbox"/>
          {Country.name}
        </label>
        {Country.Cities.map(renderCities)}
      </div>
    );
  };

function onChange(e) {
  console.log('checkbox checked:', (e.target.checked));
}

class AreasBar extends Component {
      constructor(props) {
        super(props);
        this.state = { 
        };
    }

  componentWillMount() {
    this.props.fetchAllAreas(); 
  }

  renderContinents(continent) {
      return(
        <div className="continent-bar">
          <label>
            <input
                onChange={onChange}
                type="checkbox"/>
             {continent.name}
          </label>
          {continent.Countries.map(showArea)}
        </div>
    )
  }

  render() { 
    return(
        <div> 
          {this.props.areas.map(this.renderContinents)}
        </div>
    );
  }
}

This is what I want to do. If a user clicks the checkbox of a parent (like Europe), then all of the countries and cities related to it should show up and be clicked.

This is what I'm thinking of doing and I'm wondering if this approach is acceptable for this scenario.

  1. Bind the onChange handler to the AreasBar component, add an object parameter so we know which object is selected and pass it as a prop to showArea and renderCities
  2. Add an extra field to areas called checked which sees if the checkbox was checked or not
  3. Make all checkboxes controlled and set the checked state to the state of the object in areas
  4. When onChange is called, an action creator is called to set the new checked state of the object



Aucun commentaire:

Enregistrer un commentaire