imgnx
imgnx

Reputation: 789

React: Invoking function with parameters causes infinite loop

So, I have a component that renders another component with a prop like so:

`<Component_One>
    <Component_Two onChange={this.changeSomething} />
</Component_One>`

Inside Component_One, the function changeSomething() takes one parameter: id

So inside Component_One, changeSomething() looks like this:

`changeSomething(id) {
    this.setState({something: id});
}`

Component_Two looks like this:

`<div id="componenttwo">
    <div onClick={this.props.onChange(0)}>
        <div className="badge"></div>
    </div>
    <div onClick={this.props.onChange(1)}>
        <div className="badge"></div>
    </div>
    <div onClick={this.props.onChange(2)}>
        <div className="badge"></div>
    </div>
</div>`

The object is to get this.state.something inside Component_One to equal the explicitly typed id of the div in Component_Two...

but instead it throws this error: SCRIPT5022: 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.

So how do I pass an explicitly typed argument to a "prop function" without creating an infinite loop?

Upvotes: 1

Views: 4686

Answers (3)

Behrouz Seyedi
Behrouz Seyedi

Reputation: 316

change your changeSomething function like this:

const changeSomething = (id) => (event) => {
    this.setState({something: id});
}

Upvotes: 0

learner
learner

Reputation: 4808

You need to access parameter in component one:

<Component_Two onChange={(id) => this.changeSomething(id)} />

Now calling this.props.onChange(0) will pass 0 as a value for id.

Upvotes: 1

Prakash Sharma
Prakash Sharma

Reputation: 16472

You should pass a function to onClick handler but you are calling the function. Because of that the function is called immediately and set the state which causes rerender, resulting in infinite loop. Pass a function instead like

onClick={() => this.props.onChange(0)}

Upvotes: 10

Related Questions