TransWikia.com

Update a with react

Stack Overflow Asked by Mara Oliveira on December 30, 2021

I have a tag select that could be selected but i do have a next and previous buttons that should update the option.

I tried to do that using sort() every time the buttons are clicked but when I select the option and then use the next button, the select does not update anymore.

How can I update the select option dynamically with a state and make this work?

component Select

export default function RegistroNavSelect(props) {

      const atualizarLista = (e) => {
        props.setPeriodo(e.target.value)
      }
      return (
          <select id="periodoSelec" className="registro__nav--select" name="select" onChange={e => atualizarLista(e)}>
            {props.lista?.map((periodo, index) => {
              return (<option key={index} value={periodo}>{periodo}</option>)
            })}
          </select>
        );
    }

component navigate

export default function RegistrosNav(props) {
  const periodos = props.lista
  const index = props.lista.indexOf(props.periodo)

  const setNav = (direcao) => {
    if(direcao){
      props.setPeriodo(periodos[index-1])
    }
    if(!direcao){
      props.setPeriodo(periodos[index+1])
    }
  }
  return <>
    <div className="registro__nav">
    <FontAwesomeIcon onClick={e => setNav(false)} className="registro__nav--icon" icon={faChevronLeft}/>
    <div>
      Período
      <RegistroNavSelect periodo={props.periodo} lista={props.lista} setPeriodo={props.setPeriodo}/>
     </div>
     <FontAwesomeIcon onClick={e => setNav(true)} className="registro__nav--icon" icon={faChevronRight}/>
    </div>
  </>;

One Answer

You have to ensure your <select> is a controlled component. So you should include value as an attribute on the select element. I'm assuming setPeriodo is from a useState call and the other part of the tuple is periodo. Therefore you would need to pass periodo as a prop to RegistroNavSelect and the resulting select line should be:

<select id="periodoSelec" className="registro__nav--select" name="select" onChange={e => atualizarLista(e)} value={periodo}>

Answered by Ashraf Slamang on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP