简体   繁体   中英

Updating multi-select options from state doesn't trigger material_select so options don't appear

I am updating the options of the select based on the state of my component.

The state is initially set to an empty array but once loaded from an API, the state is updated so the options should update.

While this does happen (and can be seen in the dev tools), it looks like material_select needs to be called to update how it looks.

I can get this to appear correctly by calling $("select").material_select() from the console.

I think that the line causing the issue is here: https://github.com/react-materialize/react-materialize/blob/master/src/Input.js#L38

Is there a way that I can manually call this while inside my component?

Please note that I'm using create-react-app.

<Row>
  <Input
    id="categories"
    type="select"
    label="Categories"
    multiple={true}
    onChange={this.handleChange}
    s={12}
  >
    {this.state.categories.map(category => {
      return (
        <option key={category._id} value={category._id}>
          {category.name}
        </option>
      );
    })}
  </Input>
</Row>

You can fix the problem by rendering the Input component once your options arrive from API.

You can initailize your state as null as opposed to empty array:

state = {
  categories: null;
}

So in your render method, render the component conditionally (only if options are available):

render() {
    return (
      <Row>
        {this.state.categories ? (
          <Input
            id="categories"
            type="select"
            label="Categories"
            multiple={true}
            onChange={this.handleChange}
            s={12}
          >
            {this.state.categories.map(category => {
              return (
                <option key={category._id} value={category._id}>
                  {category.name}
                </option>
              )
            })}
          </Input>
        ) : null}
      </Row>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM