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

200
Visualizações
How to enable/disable all buttons in React App using a switch/toggle button

I want to make a switch/toggle button that disables all the buttons in the app, and enables them when clicked on AND the user types in the correct password

handleToggleChange() {
    var elements=document.getElementsByClassName('MuiButtonBase-root');
    var i;
    if (this.state.lock ===  false) {
        this.setState({lock: true});
        for (i = 0; i < elements.length; i++) {
            elements[i].disabled = false;
        }
    } else {
        this.setState({lock: false});
        for (i = 0; i < elements.length; i++) {
            elements[i].disabled = true;
        }
    }
}

This is my ToggleButton Code

                       <ToggleButtonGroup onChange={this.handleToggleChange}>
                            <FormControlLabel
                                label={<Typography variant="caption">Unlock</Typography>}
                                control={<ToggleButton
                                        id="togglebutton"
                                        size="small"
                                        value="false" 
                                        color="secondary"
                                        style={{right: 5}}
                                        selected={this.state.lock === false ? false : true}
                                    >
                                    <CheckIcon /></ToggleButton>}/>
                        </ToggleButtonGroup>

The problem is that it seems to be working, but they don't actually get disabled, despite the disable property appearing when I go into the debugger. disabled

And then the disabled property disappears when the button is unchecked. enabled

I'm fairly new to javascript so I'm not even sure if this is the way I'm supposed to be doing something like this. Any help is appreciated.

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

0

Simply achieving this at a single level with props is relatively easy. However, for app-wide state that needs to be injected at any level, you most likely want to leverage React Context, which is a React lifecycle-connected state that is injectable at any level. Below is an example using the useContext hook to create a button that can be used anywhere at any level that will automatically pick up if the global disabled state has been toggled:

// Get a hook function
const { useContext, useState } = React;

const GlobalDisabledStateContext = React.createContext({ disableUI: false });

const App = () => {
  const [disableUI, setDisableUI] = useState(false);
  return (
    <GlobalDisabledStateContext.Provider value={{disableUI}}>
      <div>
        <h1>Hello world!</h1>
        <label for="toggleDisableUI">
          Toggle Disabled UI
          <input type="checkbox" name="toggleDisableUI" id="toggleDisableUI" checked={disableUI} onChange={() => setDisableUI(!disableUI)} />
        </label>
        <h2>Below is a button wired into the app context state, which can be used at any level without wiring app state through props</h2>
        <AppStateConnectedButton onClick={() => console.log('hi')}>
          Click Me
        </AppStateConnectedButton>
      </div>
    </GlobalDisabledStateContext.Provider>
  );
}

const AppStateConnectedButton = (props) => {
  const { disableUI } = useContext(GlobalDisabledStateContext);
  return (<button disabled={disableUI} {...props} />);
}

// Render it
ReactDOM.render(
  <App />,
  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>

As I noted in the comments, any sort of DOM manipulation in the context of an MV* framework like React or Angular is an antipattern under 99% of scenarios. The entire idea of MV* frameworks is that you create a data model, bind it to a view, and the all your logic is to update the data model and let the library handle updating the view. If you ever find yourself interrogating or changing DOM in an MV* framework you are likely doing something wrong.

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