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

298
Visualizações
How can I create a counter as components to use multiple times and create one button to reset all the counter in React JS?

I want to create a counter component to use multiple times and I want to create a button component or a button in the app.js to reset all the components. So I created the counter component, but I do not understand how to create the button. I created an individual reset button for each component. But I can not create the reset button which will be reset everything. I tried in many ways, but I failed.

Here is my counter component:

import { useCallback, useState } from 'react';
import Button from './Button';
import ShowCount from './ShowCount';

export default function ReactCounter({num}) {
    const [count, setCount] = useState(0);

    const resetCounter = () => {
        setCount(0);
    };

    const incrementByOne = useCallback(() => {
        setCount((prevCount) => prevCount + num);
    }, [num])

    return (
        <div className="app">
            <ShowCount count={count} title = "Counter 1" />
            <Button handleClick={incrementByOne}>Increment By One</Button>
            <Button handleClick={resetCounter}>Reset</Button>
        </div>
    )
}

This is the app.js file:

import ReactCounter from './components/ReactMeth';
import Title from './components/Title';

export default function App() {
    
    return (
        <div className="app">
            <Title />
            <ReactCounter num={10} />
            <ReactCounter num={2} />
            <ReactCounter num={1} />
        </div>
    )
}

And here is the other components:

ShowCount.js

import React from 'react';

function ShowCount ({count, title}) {
    console.log(`rendering ${title}...`);
    
    return(
        <p>
            {title}: {count}
        </p>
    )
}

export default React.memo(ShowCount);

Button.js

import React from 'react'

function Button({handleClick, children}) {
  return (
    <p>
        <button type='button' onClick={handleClick}>
            {children}
        </button>
    </p>
  )
}

export default React.memo(Button)
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use a useState to controll when to reset all the fields. This is one way to do it which is pretty basic, but does the job. It is just a useState which is connected to all the counters, and each time it changes value (which will happend when clicken on the 'reset all' button on linje 12 in App.js), the counters will use a useEffect and trigger a reset of their counter.

ReactCounter.js

import { useCallback, useEffect, useState } from "react";
import Button from "./Button";
import ShowCount from "./ShowCount";

export default function ReactCounter({ num, reset }) {
  const [count, setCount] = useState(0);

  const resetCounter = () => {
    setCount(0);
  };

  useEffect(() => {
    setCount(0);
  }, [reset]);

  const incrementByOne = useCallback(() => {
    setCount((prevCount) => prevCount + num);
  }, [num]);

  return (
    <div className="app">
      <ShowCount count={count} title="Counter 1" />
      <Button handleClick={incrementByOne}>Increment By One</Button>
      <Button handleClick={resetCounter}>Reset</Button>
    </div>
  );
}

App.js

import { useState } from "react";
import ReactCounter from "./components/ReactCounter";

export default function App() {
  const [resetAll, setResetAll] = useState(0);
  return (
    <div className="app">
      <ReactCounter num={10} reset={resetAll} />
      <ReactCounter num={2} reset={resetAll} />
      <ReactCounter num={1} reset={resetAll} />
      <button onClick={() => setResetAll(resetAll === 1 ? 0 : 1)}>
        reset all
      </button>
    </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