Home > Back-end >  Recursive React component
Recursive React component

Time:08-18

Hi I'm learning recursion and I'm trying to build a recursive react component that accepts a string as a prop and renders the reversed string.

This is what I came up with:

  const App = () => {
    const str = "Hello world!";
    return (<RecursiveComponent str={str} />);
  }

And that's my RecursiveComponent solution:

const RecursiveComponent = ({ str }) => {
  let temp = str.slice(0, str.length - 1);

  if (str.length > 0) {
    return (
      <>
        {temp[temp.length - 1]}
        <RecursiveComponent str={temp} />
      </>
    );
  }

  return <>{temp}</>;
}

However the rendered result ignores the last char in the string. So for Hello world! it renders dlrow olleH while ignoring !.

I guess it's because of temp variable. How can I fix that?

CodePudding user response:

In your recursion start, you missing logic of presenting the first char ({temp[temp.length - 1]} always shows the second char)

const RecursiveComponent = ({ str }) => {
  const lastChar = str[str.length - 1];
  const nextStr = str.slice(0, str.length - 1);

  return (
    <>
      {lastChar}
      {nextStr.length > 0 && <RecursiveReverser str={nextStr} />}
    </>
  );
};
  • Related