-1

I am using a React class based component and material UI to display the dropdown. I am originally setting a default value and the select dropdown values get changed according to user click. However, I want to change the values programmatically, for eg. - I want to do something like I change the value in a variable, eg - age=40, and the dropdown which earlier had age=30 choses, now automatically reflects the value 40. Can anyone suggest please?

I tried passing value={this.age} in the option. And changed the value of this.age to 40 somewhere in the code programatically, however the drop-down still displays the value 30 for me

2
  • Are you storing age in this.state, and updating it via this.setState? Commented Jan 11, 2023 at 18:09
  • Yes I tried via this.state.age and this.setState{age:40} in the undo event but didn't work Commented Jan 12, 2023 at 18:11

1 Answer 1

0

If you want to use <select>, the straightforward answer is:

class App extends Component {
  constructor() {
    super();
    this.state = {
      age: "10"
    };
  }

  render() {
    return (
      <div className="App">
        <button onClick={() => this.setState({ age: "40" })}>
          Set age to 40
        </button>
        <p>A dropdown:</p>
        <select
          value={this.state.value}
          onClick={(e) => this.setState({ age: e.target.value })}
        >
          <option value="10" selected={this.state.age === "10"}>10</option>
          <option value="20" selected={this.state.age === "20"}>20</option>
          <option value="30" selected={this.state.age === "30"}>30</option>
          <option value="40" selected={this.state.age === "40"}>40</option>
        </select>
      </div>
    );
  }
}

If you click on the button, the selection will change.

Sign up to request clarification or add additional context in comments.

2 Comments

I will not be clicking the button. Maybe some other event, let's say 'Undo' selection or some other event - and the value in the dropdown field needs to reflect the older value without the user clicking on the selection.
@user13569341 Button click event is just a way to show how programmatic change works. You can use any event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.