Nadav
Nadav

Reputation: 333

infinate loop while passing function as prop react

I followed some examples to pass function as prop.

Parent:

class BookList extends React.Component{
    updateBook(chosenBook){
        this.props.editBook(chosenBook); // redux func
    }

    render() {
        return ( 
            <div>
                {this.props.books.map((item, i) => (
                    <Book key={i} list={item} submitBook={this.updateBook(item)}></Book>
                ))}
            </div>;
        )
    }
}

Child:

<Button onClick={() => {this.toggle; this.props.submitBook(this.props.list);}}>Save</Button>

what I'm getting is an infinite loop, I know the problem is with parent component, any ideas/ other ways to do so?

Upvotes: 1

Views: 982

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104379

Because you are not passing the function correctly, you are passing a value. Remove the () with function name.

Write it like this:

submitBook = {this.updateBook}

See the diff here in this snippet:

function abc(){
   return 10;
}

console.log('without ()', abc);

console.log('with ()', abc());

Note: Don't forgot to bind the updateBook method in the constructor or use arrow function.

Upvotes: 2

Related Questions