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

260
Visualizações
How to change React component properties based on random events?

I saw similar questions in here, but they aren't addressing this specific issue.

I have a react function component like this,

function Overlay() {
  return <div className="off"></div>;
}

I want to change its className property later based on a click event that occurs on a Btn element. Note that the Btn element isn't a parent or a child of the Overlay element.

function Btn() {
  return <button onClick={changeOverlayProperty} ></button>;
}

So, what should "changeOverlayProperty" do to achieve the result? Is there any "react way" to do it other than relying on the usual element methods such as "getElementsByClassName"? Giving actual codes will be helpful as I'm totally new to ReactJS.

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

0

The ContextAPI can be used to send the className value to another Component:

import { createContext, useState, useContext } from 'react';
const Context = createContext("off"); // <= Create a Context so that state can be shared among different Components (including siblings)

function Overlay() {
  const { className } = useContext(Context); // Grab the className value from the Context. The value className will be set via the Btn Component's click handler
  return <div className={className}>Overlay</div>;
}

function Btn() {
  const { setClassName } = useContext(Context); // Grab the setClassName method from the Context
  return <button onClick={()=> setClassName("on")} >Change Class</button>;
}

export default function App() {
  const [ className, setClassName ] = useState("off");
  return (
    <>
    {/* Wrap the Components that need to share some value in a Context.Provider and share some values via the value prop */}
    <Context.Provider value={{ className, setClassName }}>
      <h1>React</h1>
      <Overlay />
      <Btn />
    </Context.Provider>
    </>
  );
}

<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
<style>.off { background: red } .on { background: green }</style>
<script type="text/babel">
const Context = React.createContext("off");

function Overlay() {
  const { className } = React.useContext(Context);
  return <div className={className}>Overlay</div>;
}

function Btn() {
  const { setClassName } = React.useContext(Context);
  return <button onClick={()=> setClassName("on")} >Change Class</button>;
}

function App() {
  const [ className, setClassName ] = React.useState("off");
  return (
    <Context.Provider value={{ className, setClassName }}>
      <h1>React</h1>
      <Overlay />
      <Btn />
    </Context.Provider>
  );
}

ReactDOM.render( <App />, document.getElementById("root") );
</script>

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