Skip to content

Instantly share code, notes, and snippets.

@franklsm1
Created August 3, 2018 03:28
Show Gist options
  • Save franklsm1/dc5dd024ab3e7e958f6de9d64b4c039e to your computer and use it in GitHub Desktop.
Save franklsm1/dc5dd024ab3e7e958f6de9d64b4c039e to your computer and use it in GitHub Desktop.
Before and After render prop example
import React from "react";
import PropTypes from "prop-types";
/*
* Example CarsList with no reusable code that may be duplicated elsewhere
*/
class CarsList extends React.Component {
state = {
cars: [],
isLoading: false,
};
_fetch = async () => {
const res = await fetch("api/url");
const json = await res.json();
this.setState({ cars: json, isLoading: false });
};
componentDidMount() {
this.setState({ isLoading: true }, this._fetch);
}
render() {
const { cars, isLoading } = this.state;
return (
<div>
<h3>My cards</h3>
{isLoading && <p>Loading cards m8</p>}
{cars.length > 0 && (
<ul>
{cars.map(car => (
<li key={car.id}>
{car.title}
</li>
)}
</ul>
)}
</div>
);
}
}
/*
* Example converting CarsList to reusable List render prop
*/
class List extends React.Component {
static propTypes = {
render: PropTypes.func.isRequired,
url: PropTypes.string.isRequired,
};
state = {
list: [],
isLoading: false,
};
_fetch = async () => {
const res = await fetch(this.props.url);
const json = await res.json();
this.setState({
list: json,
isLoading: false,
});
}
componentDidMount() {
this.setState({ isLoading: true }, this._fetch);
}
render() {
return this.props.render(this.state);
}
}
/*
* Example using the List render prop
*/
<List
url="https://api.github.com/users/JoaoCnh/repos"
render={({ list, isLoading }) => (
<div>
<h2>My repos</h2>
{isLoading && <h2>Loading...</h2>}
<ul>
{list.length > 0 && list.map(repo => (
<li key={repo.id}>
{repo.full_name}
</li>
))}
</ul>
</div>
)} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment