skip to Main Content

I have a select component and I can see the menu items and also select them but the component doesn’t show the selected value. It’s handle function works well becauese when I selected an item the the value in the database is updated

Here is the code part from it:

handleSelect(event){
        this.props.handleChange(event);
    }

render() {

    const values= {
        "1": translation.getText("SAMEWINDOW"),
        "2": translation.getText("NEWWINDOW"),
        "3": translation.getText("NEWTAB")
    };

    return(

        <Select
            name="code"
            value={values[this.props.data.code]}
            onChange={this.handleSelect}
        >
            {Object.keys(values).map((item) => (
                <MenuItem value={item}>{values[item]}</MenuItem>
            ))}
        </Select>
    )
}

I tried to change the object keys type from string to number, but it didn’t help

2

Answers


  1. Your are sending the value to the component.

    Create a state variable and update the state when value is changed.

    Ex – const [value, setValue] = useState("");

    then in the handleSelect update state such as

    handleSelect(e) {
         setValue(e);
    }
    

    finally, on the select component send the updated value

    <select
         name="code"
         value={values[this.props.data.code]}
         menuItem = {value}
         onChange={this.handleSelect} />
    
    Login or Signup to reply.
  2. As per the code it seems that you are using class components,
    So try to define a state which can store the selected value so that you may display that,

    state = {
      selected: null
    }
    
    handleSelect(event) {
      this.props.handleChange(event);
      this.setState({ selected: event });
    }
    
    render() {
    
      const values= {
        "1": translation.getText("SAMEWINDOW"),
        "2": translation.getText("NEWWINDOW"),
        "3": translation.getText("NEWTAB")
      };
    
      return (
        <Select
          name="code"
          value={values[this.props.data.code]}
          menuItem={this.state.selected}
          onChange={this.handleSelect}
        >
          {Object.keys(values).map((item) => (
            <MenuItem value={item}>{values[item]}</MenuItem>
          ))}
        </Select>
      )
    }
    

    You may refer the select box demo using mui with class component from here,
    https://codesandbox.io/s/425lm2479?file=/demo.js

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search