Created
March 1, 2019 07:43
-
-
Save PavanKu/35d18fa430e741c489fe0ae62f0b4892 to your computer and use it in GitHub Desktop.
Render prop pattern alternate by using React.cloneElement method.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
const ProductDetail = ({ product }) => ( | |
<React.Fragment> | |
<h2>{product.title}</h2> | |
<div>{product.description}</div> | |
</React.Fragment>); | |
class Fetch extends React.Component { | |
state = { | |
loading: false, | |
data: [] | |
} | |
componentDidMount() { | |
this.setState({loading:true}) | |
fetch(this.props.url) | |
.then(res=>res.json()) | |
.then(res => this.setState({data:res.data, loading: false})) | |
.catch(err => this.setState({loading: false})); | |
} | |
render() { | |
if(this.state.loading) { | |
return <Loader /> | |
} | |
return React.cloneElement(this.props.children, { | |
product: this.state.data | |
}); | |
} | |
} | |
class Sample extends React.Component { | |
render() { | |
return ( | |
<Fetch url={"some url"}> | |
<ProductDetail /> | |
</Fetch> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment