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

276
Visualizações
How can I toggle a boolean value inside an array which is a state in react?
const [isShown,setIsShown]=React.useState([false,"Hide"])

function toggleIsShown(){
    setIsShown(prev=>{
        prev[0]=!prev[0]
        return prev
    })
}

since I am a beginner react learner, I cannot grasp the idea of changing states. This is why I am struggling with the problem above. Again, when I press a certain button, I want to toggle the first element of "isShown"

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

0

You could do this:

function toggleIsShown(){
  setIsShown([!isShown[0], isShown[1]]);
}

But overall this array of values is just going to lead to more confusion and problems. Are these two values even related? If not, separate them:

const [isShown,setIsShown] = React.useState(false);
const [someText,setSomeText] = React.useState("Hide");

Then toggling is semantically simpler:

function toggleIsShown(){
  setIsShown(!isShown);
}

Or if these values are related, create a semantically meaningful object:

const [shownInfo,setShownInfo] = React.useState({ isShown: false, someText: "Hide" });

And update the property by name:

function toggleIsShown(){
  setShownInfo({ ...shownInfo, isShown: !shownInfo.isShown });
}

The point is that arrays are not the right structure for grouping together random values. An array should represent a collection of some particular thing. These values you have are either unrelated (should be separate) or have some kind of semantic meaning in their relation (should be an object with named properties).

about 4 years ago · Juan Pablo Isaza Relatório

0

Duplicate the state, make your adjustment, and set:

setIsShown(prev => {
    const clone = [ ...prev ];
    clone[0] = !clone[0];

    return clone;
});

Try it:

const { useState } = React;

const Example = () => {

    const [isShown,setIsShown] = useState([ false, "Hide" ])

    function toggleIsShown(){
        setIsShown(prev => {
            const clone = [ ...prev ];
            clone[0] = !clone[0];

            return clone;
        });
    }
    
    return (  
        <div>
            <button onClick={toggleIsShown}>Toggle</button>
            {
              (isShown[0])
                ? <em>Element is shown</em>
                : null
            }
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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