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)