Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda