I have a React functional component which prints a counter number being incremented or decremented on button clicks..Below is my function
I am using react version : ^16.13.1
export default function Counter(){
const [count, setCount] = useState(0);
const increment = () => {
//more logic here ..
setCount(count + 1);
}
const decrement = () => {
//more logic here ..
setCount(count !== 0 ? count - 1 : 0);
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => increment()}>Increment SO</button>
<button onClick={() => decrement()}>Decrement SO</button>
</div>
);
}
I want to separate event handlers logic that includes setting state in to a separate file and export it.. like below
import React, { useState } from 'react';
const Increment = () => {
//more logic here ..
setCount(count + 1);
}
const Decrement = () => {
//more logic here ..
setCount(count !== 0 ? count - 1 : 0);
}
export default { Increment, Decrement };
I wanted to use these exported functions in the Counter function like below
import CounterHelper from './CounterHelper';
<button onClick={() => CounterHelper.Increment()}>Increment SO</button>
I have run in to several error's while running this ,so i am sure i am missing some thing fundamental here. Can somebody please tell me if this is possible at all ? are there any alternate options to achieve the above said with functional component and react hooks only.
Thanks in advance.
Just pass the variable references.
CounterHelper.js
export const Increment = (count, setCount) => {
//more logic here ..
setCount(count + 1);
};
export const Decrement = (count, setCount) => {
//more logic here ..
setCount(count !== 0 ? count - 1 : 0);
};
Counter.js
import React, { useState } from 'react';
import { Increment, Decrement } from './CounterHelper';
export default function Counter(){
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => Increment(count, setCount )}>Increment SO</button>
<button onClick={() => Decrement(count, setCount)}>Decrement SO</button>
</div>
);
}
Update:
Using a custom hook.
useCounterState.js
export default function useCounterState() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count !== 0 ? count - 1 : 0);
};
return {count, increment, decrement}
}
Counter.js
import React, { useState } from 'react';
import useCounterState from './useCounterState';
export default function Counter(){
const { count, increment, decrement } = useCounterState();
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => increment()}>Increment SO</button>
<button onClick={() => decrement()}>Decrement SO</button>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With