Skip to content

Instantly share code, notes, and snippets.

@PavanKu
Created March 1, 2019 07:43
Show Gist options
  • Save PavanKu/35d18fa430e741c489fe0ae62f0b4892 to your computer and use it in GitHub Desktop.
Save PavanKu/35d18fa430e741c489fe0ae62f0b4892 to your computer and use it in GitHub Desktop.
Render prop pattern alternate by using React.cloneElement method.
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