How to exchange the value of Select - Materil UI

Asked

Viewed 25 times

1

Hi, would you like to know how to set a value in Select Component, Material UI, through a click? For example, by clicking the button, invoke the handleAlert function, which changes the Select value;

export default function NativeSelects() {
  const classes = useStyles();
  const [age, setState] = React.useState('');

  const handleChange = event => {
    const name = event.target.value;
    setState(name);
  };

  const handleAlert = () => {
    const teste = 'teste'
    setState(teste);
  };

  return (
    <div>
      <FormControl className={classes.formControl}>
        <InputLabel htmlFor="age-native-simple">Age</InputLabel>
        <Select
          native
          value={age}
          onChange={handleChange}
          inputProps={{
            name: "age",
            id: "teste"
          }}
        >
          <option aria-label="None" value="teste" />
          <option value={10}>Ten</option>
          <option value={20}>Twenty</option>
          <option value={30}>Thirty</option>
        </Select>
      </FormControl>
      <Button onClick={handleAlert}>Teste</Button>
    </div>
  );
}

1 answer

0

Basically, a minimal example:

import React, { useState } from "react";
import { Select } from "@material-ui/core";
import MenuItem from "@material-ui/core/MenuItem";

function App() {
  const [value, setValue] = useState(3);
  const handleChangeValue = (e) => {
    setValue(e.target.value);
  };
  return (
    <div className="App">
      <div>
        <p>{value}</p>
        <Select defaultValue={value} onChange={handleChangeValue}>
          <MenuItem value="1">Primeiro Termo</MenuItem>
          <MenuItem value="2">Segundo Termo</MenuItem>
          <MenuItem value="3">Terceiro Termo</MenuItem>
          <MenuItem value="4">Quarto Termo</MenuItem>
        </Select>
      </div>
    </div>
  );
}

export default App;

I realized that used different, but, I went by the documentation and followed the example and an important fact is to use this way to have the same effect shown in website and documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.