Select does not let you select the option

Asked

Viewed 98 times

0

Hello, I have a list of option of a select and I can’t select an item from the list.

import React, { useState, useEffect } from 'react';
import styled from 'styled-components';

export default function ListCompany(props) {

const Label = styled.label"
display: flex;
align-items: center;
padding: .375rem .75rem;
margin-bottom: 0;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
white-space: nowrap;
background-color: #e9ecef;
border: 1px solid #ced4da;
border-radius: .25rem;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
text-align: center!important;
"

const Select = styled.select"
  display: block;
width: 100%;
height: calc(1.5em + .75rem + 2px);
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
position: relative;
flex: 1 1 auto;
width: 1%;
margin-bottom: 0;
 "

const [company, setCompany] = useState([]);

useEffect(async () => {
 const response = await fetch('http://localhost:57248/api/listaempresas');
const data = await response.json();

setCompany(data);
}, []);

return (
<div className="input-group mb-3">
  <div className="input-group-prepend">
    <Label htmlFor={props.id} >{props.texto}</Label>
  </div>
  <Select className="" id={props.id} required="required" onChange={props.change}>
    <option value={0}>Escolha...</option>
    {company.map(function (empresa) {
      return (<option key={empresa.ax_cod_empresa} value={empresa.ax_cod_empresa}>{empresa.ax_desc_empresa}</option>);
    })
    }
  </Select>
</div>
  )
}

This would be the Select that is rendered:

inserir a descrição da imagem aqui

It lets me see the options but does not let select. When I click it goes back to the Escolha...

As requested here is the rest of the code:

<ListCompany
 id="empresa"
 texto="Empresa: "
 change={this.handleCompanyChange}
 errorText={this.state.companyError}
/>

This is the handleCompanyChange:

handleCompanyChange(e) {
 var g = document.getElementById("empresa");
 var result = g.options[g.selectedIndex].value;
 this.setState({ empresa: result });
}
  • Gabriel, your onChange function is coming from a component above this one (props.change), so you need to display it to understand what’s going on. And the most important thing there is that we’re missing Value for Select which should possibly come by props tbm.

  • As requested, I have placed the snippets corresponding to the function call and change.

2 answers

1


Gabriel, I believe you could do it differently using the React api better. I would do the following: Where it has its function handleCompanyChange:

import React, { useState, useEffect } from 'react';
import ListCompany from './ListCompany'
export default function SeuComponente() {
  const [company, setCompany] = useState([]);
  const [value, setValue] = useState(null);

  useEffect(async () => {
    const response = await fetch('http://localhost:57248/api/listaempresas');
    const data = await response.json();
    setCompany(data);
  }, []);

  return (
    <div>
    {/* Deve ter alguma coisa aqui pra exibir... */}
    <ListCompany
       id="empresa"
       texto="Empresa: "
       change={(e) => setValue(e)}
       value={value}
       companies={company}
       errorText={'sua validação de erro...'}
    />
    </div>
  );

}

The Listcompany component would look something like this:

import React from 'react';
import styled from 'styled-components';

// Seus styles devem vir antes de declarar a função para
// evitar renderização das variáveis desnecessariamente.

const SeuEstiloVemAqui = styled.label``; // use 'crase' ao invés de aspas

export default function ListCompany(props) {

return (
<div className="input-group mb-3">
  <div className="input-group-prepend">
    <Label htmlFor={props.id} >{props.texto}</Label>
  </div>
  <Select
    className=""
    id={props.id}
    required="required"
    onChange={(e) => props.change(e.target.value)}
    value={props.value}
    >
      <option value={0}>Escolha...</option>
        {props.companies.map(empresa => (
          <option
            key={empresa.ax_cod_empresa}
            value={empresa.ax_cod_empresa}
          >
            {empresa.ax_desc_empresa}
          </option>
        ))}
  </Select>
</div>
  )
}

You would just have to see how your Select gets the values. This seems to be a stylized Select of some lib and some receive value as an object {label: '', value: ''}

0

Here is an example of Select that I use:

 class Teste extends Component {
 
  state = {
    assunto: "",
  };
 
 alterar = e => {
    this.setState({ [e.target.name]: e.target.value });
  };
 
 render() {
  const { ocorrencias } = this.props;
  return (
  <div>
  <select id="assunto" name="assunto" className="form-control"  onChange={this.alterar}>
                  <option value="0">Selecione...</option>
                  {ocorrencias.assunto.map(assunto => (
                   <option value={assunto.codigo}>{assunto.titulo}</option>
                  ))}
                </select>
			</div>	
	)
}	

}

Browser other questions tagged

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