Last active
June 28, 2019 19:24
-
-
Save matthewdavi/5b4b9cf88b4b689152221d5ed6457bff to your computer and use it in GitHub Desktop.
Recursive react component
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
/* I haven't seen anyone write about this, but I thought about it this morning in the shower and it works, why wouldn't it? | |
JSX is just sugar for function calls (React.createElement). */ | |
const Fib: React.FC<{ | |
start?: number; | |
end: number; | |
previous?: number[]; | |
}> = ({ end, start = 2, previous = [1, 1] }) => { | |
const memo = previous.concat( | |
previous[previous.length - 1] + previous[previous.length - 2] | |
); | |
if (start >= end) | |
return ( | |
<> | |
{memo.map((num, i) => ( | |
<div key={i}>{num}</div> | |
))} | |
</> | |
); | |
return <Fib end={end} start={start + 1} previous={memo} />; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a codesandbox link to demo https://codesandbox.io/s/recursive-react-8iuol