1

I'm trying to render a component recursively. On each recursive call I subtract 10 px from the dimensions. I expect a series of nested divs, each one 10px smaller. When the height and width reach 10px, the component should return null, so that is my base case.

Instead of expected result, I've got nothing. No errors in the terminal, no errors in the dev tools, just a page that is frozen.

Any thoughts?

RecurentDiv.js:

const RecurentDiv = ({ width, height }) => {
  const style = {
    width: `${width - 10}px`,
    height: `${height - 10}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  if (width < 10) return null; //base case

  return (
      <div style={style}>
        <RecurentDiv width={style.width} height={style.height} />
      </div>
  );
};

export default RecurentDiv;

App.js:

<RecurentDiv width={100} height={100} />
3
  • Please add you for loop code. Commented Feb 18, 2020 at 20:18
  • medium.com/@suraj.rajan/… will help Commented Feb 18, 2020 at 20:19
  • @SvetoslavDimitrov There isn't any "for loop code" because it's a recursive function. Commented Feb 18, 2020 at 20:34

1 Answer 1

3

The issue is here:

<RecurentDiv width={style.width} height={style.height} />
                  //^^^^^^               ^^^^^^

style.width is a string, not a number: ${width - 10}px. The code is doing "100px" - 10 which evaluates to NaN, which is then passed into the next RecurentDiv's props. The base case is never reached.

Instead, pass width and height numbers directly into the recursive component, subtracting the reduction amount to approach the base case.

Here's a minimal, complete example:

const RecurrentDiv = ({width, height}) => {
  const style = {
    width: `${width}px`,
    height: `${height}px`,
    border: "1px solid black",
    display: "inline-block"
  };

  return width < 10 ? null : (
    <div style={style}>
      <RecurrentDiv width={width - 10} height={height - 10} />
    </div>
  );
};

ReactDOM.createRoot(document.querySelector("#app"))
  .render(<RecurrentDiv width={100} height={100} />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="app"></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.