Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
How do I get the selected value from the select to another component?

I have this select component with their values taken from the useEffect data. In this component, I could see in the console the value that was selected from the select

const SelectName = () => {
  const [value, setValue] = useState(0);
  const [names, setNames] = useState([]);
  const handleChange = (e) => setValue(e.target.value);
  useEffect(() => {
    const unsubscribe = firestore
      .collection("name")
      .onSnapshot((snapshot) => {
        const arr = [];
        snapshot.forEach((doc) =>
          arr.push({
            ...doc.data(),
            id: doc.id,
          })
        );
        setNames(arr);
      });

    return () => {
      unsubscribe();
    };
  }, []);
  //   console.log(value);
  return (
    <div>
      <FormControl fullWidth>
        <InputLabel htmlFor="names">Names</InputLabel>
        <Select onChange={handleChange} fullWidth>
          {names &&
            names.map((user) => (
              <MenuItem
                key={user.firstName + " " + user.lastName}
                value={user.firstName + " " + user.lastName}
                // defaultValue={}
              >
                {user.firstName + " " + user.lastName}
              </MenuItem>
            ))}
        </Select>
      </FormControl>
    </div>
  );
};

export default SelectName;

And I have this other component with other fields, and I wanted to add the select component here. However, I cannot get the value of the selected component in this form. I would also be using the select component twice in this component; first with the 1st selected name and 2nd selected name. And there might be instances where the user might enter different names of the 1st and 2nd select.

I tried putting value and onChange on the first select component but I cannot see the selected value in the console. How would I be able to get the values from select? Thank you.

  const [value, setValue] = useState("");
  const handleChange = (e) => setValue(e.target.value);
  console.log(value);

      

 <form onSubmit={handleSubmit}>
                  //other fields
                     <Grid item>
                   //1st selected Name
                    <SelectName
                      value={value}
                      onChange={handleChange}
                    />
                  </Grid>
                   <Grid item>
                   //2nd selected Name
                    <SelectName/>
                  </Grid>
                    <ButtonForm type="submit" fullWidth>
                      Submit
                    </ButtonForm>
                  </Grid>
                </Grid>
              </form>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You should destructure the passed value and onChange props and use these instead of the local value component state.

const SelectName = ({ value, onChange }) => {
  const [names, setNames] = useState([]);

  useEffect(() => {
    const unsubscribe = firestore
      .collection("name")
      .onSnapshot((snapshot) => {
        const arr = [];
        snapshot.forEach((doc) =>
          arr.push({
            ...doc.data(),
            id: doc.id,
          })
        );
        setNames(arr);
      });

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <div>
      <FormControl fullWidth>
        <InputLabel htmlFor="names">Names</InputLabel>
        <Select
          value={value}       // <-- pass value
          onChange={onChange} // <-- pass change handler
          fullWidth
        >
          {names &&
            names.map((user) => (
              <MenuItem
                key={user.firstName + " " + user.lastName}
                value={user.firstName + " " + user.lastName}
              >
                {user.firstName + " " + user.lastName}
              </MenuItem>
            ))}
        </Select>
      </FormControl>
    </div>
  );
};

As an optimization, and to generalize further, you may want to factor out the firestore logic as well, into the parent and pass the options in as a prop.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda