React ~ Component Patterns ~ Render Props - rohit120582sharma/Documentation GitHub Wiki

Components are the primary unit of code reuse in React, but it’s not always obvious how to share the state or behaviour that one component encapsulates to other components that need that same state.

The Render Props pattern is a way to share functionality between components without repeating code. It is simply a prop whose value is a function which returns elements that will be used in render(). It is one of the advanced patterns in React (next to higher-order components). The components which implement this pattern could be called render prop components.

This pattern can be used to add flexibility into your app, making it much more resilient to change. It enhances React’s patterns for compositions. Rather than using the children directly to render them, you call it as function, because the children are passed as function to the wrapper component in the first place.

class Hover extends React.Component {
    state = { hovering: false }
    mouseOver = () => this.setState({ hovering: true })
    mouseOut = () => this.setState({ hovering: false })

    render() {
        return (
            <div onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>
                {this.props.children(this.state.hovering)}
            </div>
        );
    }
}

function App () {
    return (
        <React.Fragment>
            <Hover>
                {(hovering) => <Info hovering={hovering} />}
            </Hover>

            <Hover>
                {(hovering) => <TrendChart hovering={hovering} />}
            </Hover>

            <Hover>
                {(hovering) => <DailyChart hovering={hovering} />}
            </Hover>
        </React.Fragment>
    );
}

Dependency Injection (DI): The basic idea is, you remove hard-coded identifier from your code. For example, a function could use another function to do something, but it could also get a function reference passed into it that does something. The render prop is like a natural extension of this principle to logic. You can add new elements into the RPs to simply change what is displayed, for example change Tables to Graphs etc.



⚠️ **GitHub.com Fallback** ⚠️