Yomain
Yomain

Reputation: 145

React - passing 'this' as a prop

Is there any side effect I do not see by doing this ?

class App extends React.Component {
    hello() {
        console.log("hello")
    }

    render() {
        return <Layout app={this}>
    }
}

So later on I can refer to this.props.app.hello (and others) from Layout ?

Upvotes: 4

Views: 1509

Answers (2)

Joshua Wade
Joshua Wade

Reputation: 5293

This is not safe.

React will not know how to watch for changes, so you may miss re-renders. React uses === to check for state changes, and App will always be === to App, even when state or properties change.

Take this example:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.setState({text: 'default value'});
    }

    hello() {
        this.setState({...this.state, text: 'new value'});
    }

    render() {
        return (
            <div onClick={this.hello}>
                <Layout app={this}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.app.state.text}</div>
    }
}

When you click on the parent div, this.hello will be called, but the child component will not detect the state update, and may not re-render as expected. If it does re-render, it will be because the parent did. Relying on this will cause future bugs.

A safer pattern is to pass only what is needed into props:

class App extends React.Component {
    //...

    render() {
        return (
            <div onClick={this.hello}>
                <Layout text={this.state.text}>
            </div>
        );
    }
}

class Layout extends React.Component {
    render() {
        return <div>{this.props.text}</div>
    }
}

This will update as expected.

Upvotes: 4

Jose Vasquez
Jose Vasquez

Reputation: 1738

Answer

There's nothing wrong in passing functions as props, as I can see in your example, the only thing you have to do is make sure your function is bound to the current component like the following example

Reference

React: Passing Functions to Components

Upvotes: -1

Related Questions