Render Props

A technique for sharing code between React components using a prop whose value is a regular JS function.

A Simple Render Props Example

Example of rendering props.

import React from "react"
import Example from "./Example"

function App() {
    return (
        // Component rendering the prop 
        <div>    
            <Example renderProps = {
                function(name, bool){
                    return(
                        <h1>Hello {name}, {bool ? "Good Morning" : "Good Night"}</h1>  
                    ) 
                }
            } 
            />
        </div>
    )
}

export default App

A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

Sharing State with Render Props

We can use Render Props to achieve DRY principle & share logic between different components.

import React, {Component} from "react"
import Toggler from "./Toggler"

function Favorite() {
    return (
        // Rendering a prop within a functional component
        <Toggler render = {
        
            // Props function recieving arguments
            function(on, toggle){
                return(
                    <div>
                        <h3>Click heart to favorite</h3>
                        <h1>
                            <span 
                                onClick={toggle}
                            >
                                {on ? "❤️" : "♡"}
                            </span>
                        </h1>
                    </div>    
                )
                
            }
        }
        />
        
    ) 
}

export default Favorite

Render Props with React Children

Another way we can render props is through using react children. In this case we don't have to specify the Prop within the Component.

import React, {Component} from "react"

class DataFetcher extends Component {
    state = {
        loading: true,
        data: null
    }
    
    componentDidMount() {
        fetch(this.props.url)
            .then(res => res.json())
            .then(data => {
                this.setState({
                    data: data, 
                    loading: false
                })
                console.log(data)
            })
    }
    
    render() {
        return (
            this.props.children(this.state.data, this.state.loading)
        )
    }
}

export default DataFetcher

Last updated

Was this helpful?