Skip to content

Instantly share code, notes, and snippets.

@seanconnelly34
Created October 4, 2022 17:18
Show Gist options
  • Save seanconnelly34/284b384aa6112e8f10304c1b5a4a9065 to your computer and use it in GitHub Desktop.
Save seanconnelly34/284b384aa6112e8f10304c1b5a4a9065 to your computer and use it in GitHub Desktop.
Sum component that retruns sum, and toggles display or sum with radio buttons
import React, { useState, useMemo } from "react";
interface ISumProps {
values: number[];
}
const Sum = ({ values }: ISumProps) => {
const [showSum, setShowSum] = useState<boolean>(false);
const sum = useMemo(
() =>
values.reduce((accumulator, value) => {
return accumulator + value;
}, 0),
[values]
);
const handleShowSum = (bool: boolean) => {
setShowSum(bool);
};
return (
<>
<label>Show Sum</label>
<input
type='radio'
name='sum'
value='Show'
onChange={() => handleShowSum(true)}
/>
 <label>Hide Sum</label>
<input
type='radio'
name='sum'
value='Hide'
onChange={() => handleShowSum(false)}
/>
<span>{showSum && sum}</span>
</>
);
};
export default Sum;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment