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

265
Visualizações
lifting states up in react, button click to change text

I'm trying to understand how to "lift a state up" in React. In the below, there are two scripts, App.js and Child.js. The idea is for the h1 tag to read "starting state" when the page is loaded but change to "new state" when the button clicked. However, presently, the page displays "new state" upon load.

What am I doing wrong here? How should I properly lift the state up from Child to App such that the change occurs when the button is clicked?

const App = () => {
  const [state_, setState_] = React.useState("starting state");
  const stateHandler = (data) => {
    setState_(data);
  };

  return (
    <div className="App">
      {<Child propAttribute={state_} onClick={stateHandler} />}
    </div>
  );
};

const Child = (props) => {
  const buttonHandler = (event) => {
    props.onClick("new state");
  };

  return (
    <div>
      <h1>{props.propAttribute}</h1>
      <button onClick={buttonHandler}>Button</button>
    </div>
  );
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

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

0

Ideally your child component should be as dumb as possible. It shouldn't have its own state - the state should be given to it in its props by the parent. "Lifting state up" is documented here.

In this updated example I'm passing in an array of text to the parent component, adding that to the state, and then using a new state count to check what the child component should be showing.

function App({ data }) {
  
  // Set the states
  const [text, setText] = React.useState(data);
  const [count, setCount] = React.useState(0);
  
  // Work out whether we need to update the state
  function handleClick(data) {
    if (count < text.length - 1) {
      setCount(prev => ++prev);
    }
  }

  // Render the child with the text, and the handler
  return (
    <div className="App">
      <Child
        text={text[count]}
        handleClick={handleClick}
      />
    </div>
  );
};

// And all the child component accepts is the text
// and the handler - it has no state - it's all dealt
// with by the parent component
function Child({ text, handleClick }) {
  return (
    <div>
      <h1>{text}</h1>
      <button onClick={handleClick}>Button</button>
    </div>
  );
};

const data = ['Starting state', 'Next state'];

ReactDOM.render(<App data={data} />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='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