Home > other >  how to pass a function through multiple nested loops in react
how to pass a function through multiple nested loops in react

Time:01-22

I'm trying to pass a function called 'clicker()' through multiple nested loops. I get the following error:

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

The clicker() function follows this pathway:

app.js --> one.js --> two.js --> three.js

How can I pass this function, initiated in app.js all the way through until it gets to the last component. Note that app.js renders one and this renders two and this renders three.

here is my codesandbox.

app.js:

import React, { useState } from "react";
import One from "./components/one";

export default function App() {
  const [counter, updateCounter] = useState(0);
  let clicker = () => {
    updateCounter(counter   1);
  };

  return (
    <div className="App">
      <h1>how to pass a function through nested components in React </h1>
      <h3> {counter} </h3>
      <One passMe={clicker} />
    </div>
  );
}

and one.js

import Two from "./two";

function One(props) {
  return (
    <div className="App">
      <p> this is the nested function</p>
      <Two passMe={props.passMe} />
    </div>
  );
}
export default One;

and two.js

import React from "react";
import Three from './three'

export default function Two(props) {


  return (
    <div className="App">
<Three passMe={props.passMe} />
    </div>
  );
}

and finally three.js

import React from "react";

export default function App(props) {


  return (
    <div >
      <button passMe={props.passMe(5)}>Cliicker! </button>
    </div>
  );
}

thanks so much

CodePudding user response:

Why are you passing 5 as parameter, if the function does not support any?

Assuming you want that, you may change this:

On App.js:

const clicker = (num = 1) => {
    updateCounter(counter   num);
};

On three.js:

<button onClick={() => props.passMe(5)}>Cliicker!</button>

CodePudding user response:

Actually you are on the right track of passing a function from a parent to its nested child components. But assuming you want to update the counter whenever user clicks the button on its nested component, you might want to pass the onClick(()=> props.passMe(anyValue)) on three.js button component. This way, the function created in the parent gets invoked on every button click all the way from three.js, two.js, one.js to app.js.

  •  Tags:  
  • Related