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

123
Visualizações
Initialize a State with Props in Reactjs

I have a Modal component that receives a data set of image sources and the initial index. Each side of the Modal has navigation arrows that either increment or decrement the current index. This is a simplified version of the Modal component:

function Modal({ index, data, onClose, show }) {
  const [currIndex, setCurrIndex] = useState(index);
  return (
    <main className={show ? "Modal Open" : "Modal"}>
      <img src={data[currIndex].link} alt="ModalImage" />
      <IconContext.Provider value={{ className: "Arrows" }} >
        {currIndex < data.length - 1 && (<AiOutlineRight className="ArrowNext" onClick={() => setCurrIndex(currIndex + 1)} />)}
        {currIndex > 0 && (<AiOutlineLeft className="ArrowLast" onClick={setCurrIndex(currIndex - 1)} />)}
            </IconContext.Provider>
      <div className="ModalBackground" onClick={onClose} />
    </main>
}
export default Modal;

I am using it like so:

<Modal show={show} onClose={() => setShow(false)} data={filterData()} index={modalIndex} ></Modal>

This must be bad practice because it is not working. The state is initially always 0 and never updates when I increment or decrement it. It gets immediately reset to 0. The state is stuck at 0. The props value is being passed correctly and everything else just won't work as the initial state. Is there another way I can set the initial state in the Modal based on the selection in another component?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inside the onClick for the AiOutlineLeft and AiOutlineRight, instead of:

onClick={setCurrIndex(prevIndex => prevIndex + 1)} // -1 for the other one

it should be:

onClick={() => setCurrIndex(prevIndex => prevIndex + 1)} // -1 for the other one

In the first case, the setCurrIndex will be executed immediately when the Component gets mounted, because it is a function call: fn().

In the second case, the arrow function will be executed only upon click, because it is a function declaration: ()=> fn(), waiting to be executed after a click event.


Word of caution: be very careful when using props an the initial value for the state. Read the following resources to learn about the cases where this might be considered an anti-pattern and should be avoided:

  • React Antipatterns: Props In Initial State
  • ReactJS: Why is passing the component initial state a prop an anti-pattern?
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