Created
October 4, 2022 17:18
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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