kojow7
kojow7

Reputation: 11384

Trying to pass value to a function that has been passed as props

I have the following code. If I pass the setText function once to the MyClicker class it works fine. So, in the code below, I see the text "Second Text" show up correctly.

However, I am also wanting to pass the setText function to a grandchild class. The text "3rd Text" below never shows up.

The button shows up fine, however, it does not appear to do anything when I click it. There is no error message displayed in the console and the setText() function is not getting called.

I originally had:

<Voo setText={this.setText.bind(this)} />

instead of

<Voo setText={() => this.setText} />

but was getting the following error:

Warning: setState(...): Cannot update during an existing state transition

After looking into the cause of the error, I tried the arrow function as above, but again there is no error, and the setText function does not get invoked.

Here is a simplified version of my code:

Poo Class:

import MyClicker from './MyClicker'
import Voo from './Voo'

class Poo extends React.Component {

    constructor() {
        super();

        this.state = {
            text: "Intro Text",
        };

    }

    setText(text){
        this.setState({
            text: text
        })
    }

    render(){
        return (
            <div>
                <h2>{this.state.text}</h2>
                <MyClicker handleClick={this.setText.bind(this, "Second Text")} text="Click for 2nd Text" />

                <Voo setText={() => this.setText} />
        )
    }

}

Voo class:

import MyClicker from './MyClicker'
class Voo extends React.Component {

    render(){
        <MyClicker handleClick={this.props.setText("Third Text")} text="Click for 3rd Text" />
    }

}

MyClicker class:

class MyClicker extends React.Component {

    handleClick(){
        this.props.handleClick();
    }


    render(){
        return (
            <div onClick={this.handleClick.bind(this)}>{this.props.text}</div>
            )

    }

}

What can I do to solve this problem?

Upvotes: 0

Views: 88

Answers (2)

Modig
Modig

Reputation: 1026

You can bind your function like this. And pass the setText as below, then you will pass this and what ever needed "automatically".

If you use () you will execute setState, which will rerender your component and that will execute the state again... an endless loop has been created.

setText = (text) => {
  this.setState({
      text: text
  })
}

<Voo setText={this.setText} />

Upvotes: 0

bennygenel
bennygenel

Reputation: 24660

Voo class has a small syntax error on handleClick prop.

It should be like below;

class Voo extends React.Component {
    render(){
        <MyClicker handleClick={() => this.props.setText("Third Text")} text="Click for 3rd Text" />
    }
}

If you use it like you did the function gonna be executed rather than just passing as a prop. Parenthesizes executes the function.

Upvotes: 1

Related Questions