Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive React component

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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} />}
    </>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading